Search code examples
c++mongodbmongo-cxx-driver

how convert mongo shell command to mongocxx grammar


db.members.find( {"groupId": 115, userId: { $in: [ 1000, 1001 ] } } );

I find a lot of place, include MongoDB/GitHub. but no use, Who can tell me how to implement this query use c++, thank you very much!

as follow can not work:

auto members = bsoncxx::builder::basic::array{};
for (vector<string>::size_type i = 0; i != userIds.size(); ++i) {
        int id = std::atoi(userIds[i].c_str());
        bsoncxx::builder::basic::document doc;
        doc.append(kvp("userId", id));
        members.append(doc);
    }

auto docValue = make_document(kvp("id", gid), kvp("$in", members)));
auto res = coll.delete_many(docValue.view());

Solution

  • Did you try printing out mongocxx:to_json(docValue) to see what it looks like? I predict it doesn't look like you think. It is going to come out with something like $in : [ { 'userId' : 1001, 'userId' : 1002, ... } ].

    Instead, just append to members directly inside the loop:

    auto members = bsoncxx::builder::basic::array{};
    for (vector<string>::size_type i = 0; i != userIds.size(); ++i) {
            int id = std::atoi(userIds[i].c_str());
            members.append(id);
        }