1

How to get _id after upserting document in mongo-c-driver Or mongo-cxx-driver?

The following code snippet is from mongo-shell, Which shows the _id field in last row of WriteResult.

db.coll.update(
               { item: "ZZZ135" },
               {  item: "ZZZ135",  stock: 5,  tags: [ "database" ] },
               {upsert: true} 
              )

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 1,
    "nModified" : 0,
    "_id" : ObjectId("54455f33b247e073d7161b32")
})
4

1 回答 1

3

In mongo C driver you can use the bson_t *reply to receive the returned _id in this function:

bool mongoc_collection_command_simple (
      mongoc_collection_t       *collection,
      const bson_t              *command,
      const mongoc_read_prefs_t *read_prefs,
      bson_t                    *reply,
      bson_error_t              *error
)

The equivalent in C++ is BSONObj *info in this function:

bool mongo::DBClientWithCommands::simpleCommand (
        const std::string &     dbname,
        BSONObj *   info,
        const std::string &     command 
)    
于 2014-10-20T22:57:55.423 回答