Home > Enterprise >  Mongodb nested query doesn't give result when operators are involved
Mongodb nested query doesn't give result when operators are involved

Time:10-04

Rrunning the following snippet I would expect all of the finds to return the same result, however the middle on does not find any elements. Why doesn't the second case find anything and is there any way to use the nested element notation instead of dot notation with the mongodb operators?

from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client['db']
collection = db["test_collection"]
collection.insert_one({"data": {"foo": "bar"}})

# {'_id': ObjectId('633aad8b587bc8057e240c96'), 'data': {'foo': 'bar'}}
print(collection.find_one({"data": {"foo": "bar"}}))

# None
print(collection.find_one({"data": {"foo": {"$in": ["bar"]}}}))

# {'_id': ObjectId('633aad8b587bc8057e240c96'), 'data': {'foo': 'bar'}}
print(collection.find_one({"data.foo": {"$in": ["bar"]}}))

CodePudding user response:

Why doesn't the second case find anything?

The second query is using embedded document syntax to search for documents. As you mentioned, dot notation is the alternative syntax. Both are documented here.

Each approach has different semantics. The second query that you are asking about is searching for a document that has exactly this object for its data field:

{
  foo: {
    $in: [
      "bar"
    ]
  }
}

Check out this playground demonstration which shows this behavior with more example documents.

Of course that's not what you want which is one of the reasons the alternative dot notation syntax is available.

is there any way to use the nested element notation instead of dot notation with the mongodb operators?

As written, the answer to that question is: no. As we explored above, querying using embedded syntax results in the following semantics (taken from the documentation):

Equality matches on the whole embedded document require an exact match of the specified <value> document, including the field order.

Usage of query operators, which aren't intended for this syntax, is going to result in them getting interpreted as literal field names when searching the collection. But even your first example query probably isn't generally useful as the document embedded in data could not have any other fields as demonstrated in this playground

  • Related