2

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.

Harry
  • 52,711
  • 71
  • 177
  • 261

2 Answers2

2

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.

Community
  • 1
  • 1
Joe Doyle
  • 6,363
  • 3
  • 42
  • 45
1

ElemMatch should do the trick.

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

daveh
  • 3,586
  • 1
  • 20
  • 13
  • I actually need to have both of these ids in the document. This matches other documents as well. This document is the chat document for these 2 users so I need both of them. – Harry Jun 26 '13 at 06:52