2016-09-27 91 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的圖集連接它不是拉出數據,謝謝你的幫助,我會發現錯誤 –