查询子文档数组

时间:2015-01-31 12:52:32

标签: mongodb

我有一个chatRooms集合如下:

{ "name" : "Room1", "users" : [  {  "userId" : 1 },  {  "userId" : 2 } ] }
{ "name" : "Room2", "users" : [  {  "userId" : 1 },  {  "userId" : 4 } ] }
{ "name" : "Room3", "users" : [  {  "userId" : 2 },  {  "userId" : 3 } ] }
{ "name" : "Room4", "users" : [  {  "userId" : 2 },  {  "userId" : 1 } ] }

现在我想要userId 1和2所在的房间。 我应该得到1号和4号房间。

我尝试了不同的东西,比如

db.chatRooms.find({users: {$elemMatch: {userId: 1, userId: 2}}})

但没有任何效果。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您应该使用$all运算符

db.chatRooms.find({users: 
    {$all : [
       {$elemMatch: {userId: 1}}
      ,{$elemMatch: {userId: 2}}
    ]}
})

简化版

db.coll.find({users: 
    {$all : [
       {userId: 1}
      ,{userId: 2}
    ]}
})
相关问题