Marc Alexander
Marc Alexander

Reputation: 821

Mongoose, Node JS, MongoDB and or query not working

I'm running MongoDB version v3.6.8, Node v8.12.0 & Mongoose v5.4.4.

This purely OR query produces results:

db.messages.find( { $or : [ { senderId : "5c97ca3eed0cc17e8cfb0486" }, { receiverId : "5c8430effe7df210ee3264bf" } ] })

This AND OR query doesn't return any results:

db.messages.find( { $and : [ { $or : [ { senderId : "5c8430effe7df210ee3264bf" }, { receiverId : "5c97ca3eed0cc17e8cfb0486" } ] }, { $or : [ { senderId : "5c97ca3eed0cc17e8cfb0486" }, { receiverId : "5c8430effe7df210ee3264bf" } ] } ] } )

Although since it's an AND OR query if should return results because one OR query did. Am I missing something here? Is there a fault in my AND OR query? I went straight from the Mongo docs here: https://docs.mongodb.com/manual/reference/operator/query/and/

Any help would be much appreciated!

Upvotes: 0

Views: 124

Answers (2)

Giuan Adauto
Giuan Adauto

Reputation: 109

For the AND operator in your query to be true, both OR expressions must be true. the first expression is probably returning false.

Upvotes: 1

Marc Alexander
Marc Alexander

Reputation: 821

For anyone who runs into the same problem in the future I mixed the $and & $or around so the correct query would be:

db.messages.find( { $or : [ { $and : [ { senderId : "5c8430effe7df210ee3264bf" }, { receiverId : "5c97ca3eed0cc17e8cfb0486" } ] }, { $and : [ { senderId : "5c97ca3eed0cc17e8cfb0486" }, { receiverId : "5c8430effe7df210ee3264bf" } ] } ] } )

Upvotes: 0

Related Questions