How do I update MongoDB BSON field value and add a new field in C++?

149 views
Skip to first unread message

johnsam

unread,
Apr 22, 2014, 5:25:02 PM4/22/14
to mongod...@googlegroups.com

I was trying to modify a field in a BSON object, add a new field. I was only able to append the new field but failed to update the existing field. Please advise. Thanks,

const char * ns1 = "mytest.c1";
const char * ns2 = "mytest.c2";

// test insert
conn.insert( ns1 ,BSON( "name" << "eliot" << "num" << 1 ) );
conn.insert( ns1 ,BSON( "name" << "sara" << "num" << 2 ) );
{
    auto_ptr<DBClientCursor> cursor = conn.query( ns1 , BSON( "num" << 1 ) );
    int count = 0;
    while ( cursor->more() ) {
        count++;
        BSONObj obj = cursor->next();
        BSONElement e = obj.getField("name");
        string v ("john");
        e.Val(v);
        BSONObjBuilder b;
        b.appendElements(obj);
        b.append("room", 123);
        conn.insert( ns2, b.obj()  );
    }
}

mongos> db.c1.find()
{ "_id" : ObjectId("5356d3e08b391dea54e2d3f4"), "name" : "eliot", "num" : 1 }
{ "_id" : ObjectId("5356d3e18b391dea54e2d3f5"), "name" : "sara", "num" : 2 }
mongos> db.c2.find()
{ "_id" : ObjectId("5356d3e08b391dea54e2d3f4"), "name" : "eliot", "num" : 1, "room" : 123 }

Asya Kamsky

unread,
Apr 27, 2014, 11:35:21 PM4/27/14
to mongodb-user
Normally the way to update a field is via an update statement, not by reading it, doing something to it and then saving it (as it's not atomic).

It sort of looks like you aren't really updating as you are saving it to another collection?   In any case, check out update and $set operator for updating fields (existing or not).   There are more examples on this page.

Asya




--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at http://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/fd26268b-ae5e-4af4-97f0-2b90de9750c5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages