Implicit and vs and

How come the following:

  1. db.zips.find({"$and":[{"pop":{"$lt":100000}},{"pop":{"$gt":5000}}]}).count()
  2. db.zips.find({"pop":{"$lt":100000},"pop":{"$gt":5000}}).count()

return different values?

A query is a JSON document. In principal, you cannot have 2 fields with the same key. Some drivers and languages allow it but some only keep the last occurrence, In this case, for number 2, with the shell you get:

mongo> db.zips.find({"pop":{"$lt":100000},"pop":{"$gt":5000}}).explain().queryPlanner.parsedQuery
{ "pop" : { "$gt" : 5000 } }

You may express the query of #1 with implicit AND as:

mongo> db.zips.find({ "pop" : { "$lt" : 100000 , "$gt" : 5000} }).explain().queryPlanner.parsedQuery
{
	"$and" : [
		{
			"pop" : {
				"$lt" : 100000
			}
		},
		{
			"pop" : {
				"$gt" : 5000
			}
		}
	]
}
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.