3

The following code works, what it does is: it reads from a buffer and appends to the "s" field in Mongo, but makes a call to the database every time I go through the loop:

bsonData = BSON("$push"<<BSON("s" << BSON("r" << (unsigned int)RecordNumber << "t" << Variant << "u" << TimeStamp << "v" << Value)));

What I would like to do is fill a vector with the 4 values, and insert that vector into the database in one call, I tried this:

for(i=0;i<vRecNo.size();i++)
{
    bOB.append("s", BSON("r" << (unsigned int)vRecNo[i] << 
                            "t" << (unsigned int)vType[i] << 
                            "u" << (unsigned int)vTimeStamp[i] << 
                            "v" << (unsigned int)vValue[i]));
}

but creates duplicate "s" field in Mongo. Any help is greatly appreciated, thank you in advance.

3 Answers 3

6

I am not entirely clear as to what you are asking but judging from the title I will try to offer help.

There are two ways to create BSON arrays in mongo with C++ :

  1. Use BSON_ARRAY macro like BSON macro, but without keys. Eg.

    BSONArray arr = BSON_ARRAY( "hello" << 1 << 2 << BSON( "foo" << BSON_ARRAY( "bar" << "baz" << "qux" ) ) );

    The above example will create an array with four values, where the last element is a BSON document with 3 array values

    [ "hello", 1, 2, { foo : ["bar", "baz", "qux"] } ]

  2. Use BSONArrayBuilder to build arrays without the macro. Eg.

    BSONArrayBuilder b; BSONArray arr = b.append(1).append(2).arr();

    This will create an array with 2 values [ 1, 2 ]

So in your cause, if you want to create a vector with 4 values, you should create an array, using one of the methods described above, assign that array to "s" and then insert the resulting document. That will give you something of this form { s : [ value1, value2, value3, value4 ] }

Sign up to request clarification or add additional context in comments.

Comments

2

Thank you for the hint, I finally figured it out and I'm posting the piece of code that worked for me:

   BSONObjBuilder bOb;
   BSONArrayBuilder bArr;
   for(i=0;i<vRecNo.size();i++)
    {
      BSONObj bo = BSON("r" << (unsigned int)vRecNo[i] << "t" << vType[i] << "u" << (unsigned int)vTimeStamp[i] << "v" << vValue[i]);
      bArr.append(bo);
    }
  bOb.append("s", bArr.arr());
  BSONObj bsonData = BSON("$set" << bOb.obj());

  conn.update("DatabaseName.Collection", qryData, bsonData);

Comments

0

You could convert the vector into std::list and append the list:

std::list<std::string> aList(aVec.begin(),avec.end())
BSONArrayBuilder arrBuilder;
arrBuilder.append(aList);

It is strange that you can append a std::list but not a std::vec.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.