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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

ElemMatch should do the trick.

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.