2014-10-20 78 views
1

如何在mongo-c-driver或mongo-cxx-driver中插入文档后得到_id如何在mongo-c-driver或mongo-cxx-driver中插入文档后获得`_id`?

以下代码片段来自mongo-shell,其中显示最后一行WriteResult中的_id字段。

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

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

回答

3

在蒙戈C驱动就可以使用bson_t *reply接收_idthis 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 
) 

在C++中的等价物BSONObj *infothis function

bool mongo::DBClientWithCommands::simpleCommand (
     const std::string &  dbname, 
     BSONObj * info, 
     const std::string &  command 
)