MongoDB 条件查询

MongoDB conditional query

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

猫鼬模式

 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"

您只需要一个 $or 条件,因为它需要一个数组,您可以将两个字段都放入其中。来自 MongoDB 文档中的示例:

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

所以您需要做的就是:

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