AND occasionally produces wrong result on shell and node native driver

Viewed 17

I’ve built a dynamic query generator to create my desired queries based on many factors, however, in rare cases it acted weird. After a day on reading logs I found a situation that can be simplified in this:

db.users.find({att: ‘a’, att: ‘b’})

What I expect is that mongodb by default uses AND, so above query’s result should be an empty array. However, it’s not! But when I use AND explicitly, the result is an empty array

db.users.find({$and: [{att: 'a'}, {att: ‘b'}]})
1 Answers

In javascript object’s keys should be unique, otherwise the value will be replaced by the latest value (also mongodb shell is based on js, so it follows some rules of js)

const t = {att: 'a', att: 'b'};
console.log(t);

So in your case your query is acting like this:

db.users.find({att: ‘b’})

You’ve to handle this situation on your code if you want the result be empty in the mentioned condition

Related