Harry
Harry

Reputation: 54939

Mongodb querying from part of object in array

Here's the sample document I'm trying to query

{
   "_id":"asdf0-002f-42d6-b111-ade91df09249",
   "user":[
      {
         "_id":"14bfgdsfg0-3708-46ee-8164-7ee1d029a507",
         "n":"aaa"
      },
      {
         "_id":"aasdfa89-5cfe-4861-8a9a-f77428158ca9",
         "n":"bbb"
      }
   ]
}

The document has 2 user references and contains the user _id and other misc information. I have the 2 user ids and am trying to get this document via only the user ids. I also don't know the order of the 2 ids. Is this a possible query?

col.findOne({
   user:{
      $all:[
         {
            _id:"14bfgdsfg0-3708-46ee-8164-7ee1d029a507"
         },
         {
            _id:"aasdfa89-5cfe-4861-8a9a-f77428158ca9"
         }
      ]
   }
})

^^ Something that I've tried that doesn't work.

Upvotes: 2

Views: 93

Answers (2)

Joe Doyle
Joe Doyle

Reputation: 6383

You are close with your $all attempt.

col.findOne({
   "user._id":{
       $all : [ "14bfgdsfg0-3708-46ee-8164-7ee1d029a507", 
            "aasdfa89-5cfe-4861-8a9a-f77428158ca9" ]

   }
}

You can query a sub-document by wrapping it quotes. From there $all works against the values you are looking for.

Mongodb find a document with all subdocuments satisfying a condition shows a variation on this type of query.

Upvotes: 2

daveh
daveh

Reputation: 3696

ElemMatch should do the trick.

col.findOne({user:{$elemMatch:{"_id":"14bfgdsfg0-3708-46ee-8164-7ee1d029a507", "_id":"aasdfa89-5cfe-4861-8a9a-f77428158ca9" }}})

Upvotes: 1

Related Questions