0

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.

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

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

     })

Sample Conversation Object

_id: "57eae04c4efbb25487a00293"

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

userOne: "57e334c00e5fcc9e8e800178"

userTwo: "57e334af0e5fcc9e8e800177"

1 Answer 1

1

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:

db.getCollection('conversations').find({
    $or: [
        {userOne: "57e334af0e5fcc9e8e800177"},
        {userTwo: "57e334af0e5fcc9e8e800177"}
    ]
});
Sign up to request clarification or add additional context in comments.

1 Comment

thank you its works on my development server but when I'm connecting with MongoDB atlas it's not pulling the data out thank you for your help i will find the error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.