c++mongodbmongo-cxx-driver

fin in BSON documents with MongoDB C++ driver


I have the following document in my MongoDB test database:

    db.a.find()
   {[ {
        "_id" : ObjectId("5113d680732fb764c44qweq"),
        "Builds" : [
                {
                    "level" : 1,
                    "rank" : 2
                },
                {
                    "level" : 3,
                    "rank" : 4
                }
              ]
}, {
 "_id" : ObjectId("5113d680732fb764c4464fdf"),
        "Builds" : [
                {
                    "level" : 3,
                    "rank" : 5
                },
                {
                    "level" : 3,
                    "rank" : 4
                }
              ]
    }
]}

I need find level which => 1 and <= 2 May you help me? It is possible do with mongocxx?


Solution

  • mongocxx::cursor cursor = collection.find(
      document{} << "Builds.level" << open_document <<
        "$gte" << 1 <<
        "$lte" << 2
      << close_document << finalize);
    
    for(auto doc : cursor) {
      std::cout << bsoncxx::to_json(doc) << "\n";
    }
    

    The mongo raw query which would fetch is the following :

    db.a.find({"Builds.level":{$gte:1}, "Builds.level":{$lte:2}})