2016-09-27 90 views
0

我们想要使用两个字段(id)查询集合来查找具有userOne和/或userTwo的具有相同id号的特定对话,就像我们想要查找在userOne或userTwo中具有57e334af0e5fcc9e8e800177 id的所有对话一样MongoDB条件查询

,我们试图猫鼬架构

userOne: {type: mongoose.Schema.Types.ObjectId, ref:'users'}, 
     userTwo: {type: mongoose.Schema.Types.ObjectId, ref:'users'}, 
     created_at: {type: Date, default: Date.now} 

查询。

db.getCollection('conversations').find({ 

     $or : [{userOne: "57e334af0e5fcc9e8e800177"}], 
     $or : [{userTwo: "57e334af0e5fcc9e8e800177"}] 

    }) 

样品谈话对象

_id: "57eae04c4efbb25487a00293" 

created_at: "2016-09-27T21:10:36.236Z" 

userOne: "57e334c00e5fcc9e8e800178" 

userTwo: "57e334af0e5fcc9e8e800177" 

回答

1

你仅仅是因为它带有一个数组,你可以把你的两成田需要一个$or条件。从MongoDB的文档上的例子:

db.inventory.find({ $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] }) 

因此,所有你需要做的是:

db.getCollection('conversations').find({ 
    $or: [ 
     {userOne: "57e334af0e5fcc9e8e800177"}, 
     {userTwo: "57e334af0e5fcc9e8e800177"} 
    ] 
}); 
+0

谢谢你的作品我的开发服务器上,但是当我用MongoDB的图集连接它不是拉出数据,谢谢你的帮助,我会发现错误 –