rsmets
rsmets

Reputation: 919

Query Nested Mongo Array

Not sure how to query for matching directory_object_ids for a mongo db object with the follow structure.

"_id" : ObjectId("5702e52e51c2e40f55b3fd43"),
"_revision" : 4,
"enabled" : true,
"selector" : {
    "directory_object_ids" : [
        ObjectId("56c4bfb793e0be0eb6297369"),
        ObjectId("56c4bfc293e0be0eb6297391"),
        ObjectId("56cdfc65f2325d0e6346b7fe")
    ]
}

I've tried

db.policies.find({"selector":{"directory_object_ids":{$elemMatch: {$eq:ObjectId("56cdfc65f2325d0e6346b7fe")}}}}).pretty()

and

db.policies.find({"selector":{"directory_object_ids": {$eq:ObjectId("56cdfc65f2325d0e6346b7fe")}}}).pretty()

with no luck.

Thank you in advance.

Upvotes: 0

Views: 69

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45523

Call directly the nested object in your find query :

db.policies.find({"selector.directory_object_ids": ObjectId("56cdfc65f2325d0e6346b7fe")}).pretty()

If you want to request records matching at least one among all specified item, use $in :

db.policies.find({
    "selector.directory_object_ids": {
        $in: [ObjectId("56c4bfc293e0be0eb6297391"), ObjectId("56cdfc65f2325d0e6346b7fe")]
    }
}).pretty()

And if you want to request records matching all specified items, use $all :

db.policies.find({
    "selector.directory_object_ids": {
        $all: [ObjectId("56c4bfc293e0be0eb6297391"), ObjectId("56cdfc65f2325d0e6346b7fe")]
    }
}).pretty()

Upvotes: 5

Related Questions