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.

4

2 回答 2

2

您的 $all 尝试已接近尾声。

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

   }
}

您可以通过将引号括起来来查询子文档。从那里 $all 适用于您正在寻找的值。

Mongodb 查找所有子文档都满足条件的文档显示了此类查询的变体。

于 2013-06-26T16:54:09.030 回答
1

ElemMatch应该可以解决问题。

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

于 2013-06-26T06:37:39.483 回答