Writing query for array in c++


I’m trying to follow this tutorial > https://blog.mlab.com/2018/09/use-push-to-insert-elements-into-an-array/
Mainly >

> db.alphabet.insert({
      "_id": "22222", 
      "array": ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
// We missed the 'i'!
// Let's add it in the position before the last element.
> db.alphabet.update(
      { "_id": "22222" },
          $push: {
              array: {
              $each: ['i'],
              $position: -1
// Check the results:
> db.alphabet.find({ "_id": "22222" })
{ "array" : [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" ] }v

I’m trying to reproduce it in c++ but I’m lost… can any1 guide me somehow?

    auto replace = coll.update_one(make_document(kvp("_id", bsoncxx::oid("5f3289b7807200001f002b35"))),
                                   make_document(kvp("$push", make_document(

Can any1 help out?


Hi @Dariusz_D, and welcome to the forum!

There are few ways to build a document in mongocxx, one of them is using the document builder. For more information see mongocxx: Working with BSON.

For example you could utilise Stream Builder to construct the push document. i.e.

using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;


auto builder = document{};
bsoncxx::document::value update_statement = builder
        << "$push" << open_document
            << "arrayNameTest" << open_document
                << "$each" << open_array
                    << "i" 
                << close_array
                << "$position" << -1
            << close_document
        << close_document
        << finalize;
auto result = collection.update_one(make_document(kvp("_id", "101")), update_statement.view());

See also mongocxx: Update Documents for more examples.


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