Kautilya Kondragunta
Kautilya Kondragunta

Reputation: 155

MongoDB - match all nested object property paths dynamically

enter image description here

The above is the structure of my data in the MongoDB Store. Let's say im querying as follows

{'symbol_alerts.[CHANNEL_ID_STRING].usdt_alerts: {$exists: true}}

I want to dynamically match all the CHANNEL_ID_STRINGS inside the symbol_alertspath, so i can query the existence of usdt_subs within all the channels. Any idea how i can match all CHANNEL_ID_STRINGs regardlelss of its value?

Upvotes: 1

Views: 663

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Solution #1:

var CHANNEL_ID_STRING = "abc"

var condition = {}

condition[`symbol_alerts.${CHANNEL_ID_STRING}.usdt_alerts`] = { $exists: true };

db.dynamicKeys.find(condition);

Solution #2 based on this answer:

let CHANNEL_ID_STRING = "abc";

db.dynamicKeys.aggregate([
    {
        $project: {
            dynamicKeys: { $objectToArray: "$symbol_alerts" }
        }
    },
    {
        $match: {
            "dynamicKeys": {
                $elemMatch: {
                    k: CHANNEL_ID_STRING,
                    "v.usdt_alerts": { $exists: true }
                }
            }
        }
    },
    {
        $project: {
            "symbol_alerts": { $arrayToObject: "$dynamicKeys" }
        }
    }
]);

And this how my sample collection looks like:

/* 1 createdAt:2/24/2021, 8:08:54 PM*/
{
    "_id" : ObjectId("603664fe24f3423874ac9534"),
    "symbol_alerts" : {
        "jkl" : {
            "other_key" : {
                "key1" : "value1"
            }
        },
        "mno" : {
            "usdt_alerts" : {
                "key1" : "value1"
            }
        }
    }
},

/* 2 createdAt:2/24/2021, 8:08:54 PM*/
{
    "_id" : ObjectId("603664fe24f3423874ac9533"),
    "symbol_alerts" : {
        "abc" : {
            "usdt_alerts" : {
                "key1" : "value1"
            }
        },
        "def" : {
            "other_key" : {
                "key1" : "value1"
            }
        },
        "ghi" : {
            "usdt_alerts" : {
                "key1" : "value1"
            }
        }
    }
}

Upvotes: 2

Related Questions