Edwin Ca Edwin Ca - 1 year ago 117
Node.js Question

MongoDB conditional query

We want to query a collection using two fields (ids) to find a specific conversation that has userOne and or userTwo with same id number like we want to find all the conversations that has 57e334af0e5fcc9e8e800177 id in userOne or userTwo

Mongoose Schema

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

Query that we tried.


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


Sample Conversation Object

_id: "57eae04c4efbb25487a00293"

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

userOne: "57e334c00e5fcc9e8e800178"

userTwo: "57e334af0e5fcc9e8e800177"

Answer Source

You only need a single $or condition because it takes an array which you can put both your fields into. From the example on the MongoDB documentation:

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

So all you'd need to do is:

    $or: [
        {userOne: "57e334af0e5fcc9e8e800177"},
        {userTwo: "57e334af0e5fcc9e8e800177"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download