Search code examples
mongodbmongodb-compassmongo-cxx-driver

mongocxx: How to filter documents by a field that is a member of another field/object?


In MongoDB Compass, if I filter with the following:

{'obj1.obj2.str': "thirteen"}

It retrieves successfully, every document that has obj1, and inside of obj1, obj2, and within obj2, a field called str, whose value is equal to "thirteen".

In mongocxx, If I do:

mongocxx::cursor cursor = coll.find(document{} << 
"obj1.obj2.str" << "thirteen" << finalize);

It does not find anything, (cursor.begin() will be equal to cursor.end()).

If I insert a document that is just the document id itself + one other field:

{"_id":{"$oid":"60008e7b1ccb5846d437f1c1"},"plswork":"result"}

Then I go into my C++ program and do this:

mongocxx::cursor cursor = coll.find(document{} << 
"plswork" << "result" << finalize);

It will find exactly just that document.

Also, I am able to access "str" by grabbing ALL documents using:

mongocxx::cursor cursor = coll.find({});

Then iterating through every document in collection. I can clearly see what the inner fields are within obj1 and obj2 at that point. But I wanted to grab only the documents where that inner field str is equal to the one I give it, not all docs in the collection.

What am I doing wrong to not be able to access fields within objects in my document?

I am using mongocxx 3.6.5, and MongoDB 4.4.12.


Solution

  • I figured it out. It seems to have been corrupted data or something similar to that, so mongocxx couldn't do filters on those corrupted documents, regardless of the query as long as the query wasn't empty ({} would work). Any new documents I insert from now on DO work with:

    mongocxx::cursor cursor = coll.find(document{} << 
    "obj1.obj2.str" << "thirteen" << finalize);
    

    The old data doesn't so I will just discard it and move on.