MongoDB C++ 數組的寫操作

來源:互聯網
上載者:User

經常會碰到這類問題,現在將前兩年自己寫過的代碼總結一下,以後編程會方便很多。

Document中包含兩個數組,一個簡單點,每個元素都是string,一個複雜點,每個元素都是一個對象,有兩個屬性address和status.

> db.schedule.findOne({"_id" : ObjectId("51e930f92291307bb05a1a84")}){"_id" : ObjectId("51e930f92291307bb05a1a84"),"direction" : 2,"messages" : ["m1","m2","m3"],"receivers" : [{"address" : "000000000020","status" : "waiting"},{"address" : "000000000018","status" : "waiting"}],"speed" : 3,"start_time" : "1374236921","stay_time" : 1,"user_id" : ObjectId("518b7fc5117e87bce28f2444")}

c++代碼如下:

這個函數填充簡單的數組,用到了BSONArrayBuilder. 注意其示範了insert方法的使用。

string AddScheduledMessage(ScheduledMessage const& m) {  shared_ptr<mongo_session> mongo_session = mongo_session_factory::get_session();  BSONObjBuilder data_builder;  OID _id = OID::gen();  data_builder.append("_id", _id);  data_builder.append("user_id", mongo::OID(m.user_id));  data_builder.append("start_time", m.start_time);  data_builder.append("direction", m.direction);  data_builder.append("speed", m.speed);  data_builder.append("stay_time", m.stay_time);  BSONArrayBuilder msgs_builder;  size_t size = m.msgs.size();  for (size_t i = 0; i < size; ++i) {    msgs_builder.append(m.msgs[i]);  }  data_builder.append("messages", msgs_builder.arr());  mongo_session->get().insert("db.schedule", data_builder.obj());  return _id.str();}

第二個函數添加了較複雜的數組,同時示範了update方法的使用。這個方法,假定receivers數組還不存在,採用$set命令進行設定。

void AssignScheduledMessages(ScheduledMessages & ms) {  shared_ptr<mongo_session> mongo_session = mongo_session_factory::get_session();  vector<shared_ptr<ScheduledMessage> >::iterator itor, last = ms.values.end();  for (itor = ms.values.begin(); itor != last; ++itor) {    shared_ptr<ScheduledMessage> m = *itor;    BSONObjBuilder condition;    condition.append("user_id", OID(m->user_id));    condition.append("_id", OID(m->id));    BSONArrayBuilder arr_builder;    size_t size = m->receivers.size();    for (size_t i = 0; i < size; ++i) {      BSONObjBuilder rec;      rec.append("address", m->receivers[i]->address);      rec.append("status", m->receivers[i]->status);      arr_builder.append(rec.obj());    }    BSONObjBuilder recs;    recs.append("receivers", arr_builder.arr());    BSONObjBuilder set;    set.append("$set", recs.obj());        mongo_session->get().update("db.schedule", mongo::Query(condition.obj()), set.obj());  }}

再複雜點。現在想修改一下address為00...20的那個元素的status="sending"。具體原理參考:

http://stackoverflow.com/questions/9247007/mongodb-update-the-specific-element-from-subarray

下面示範JavaScript代碼:

db.schedule.update({"_id" : ObjectId("51e930f92291307bb05a1a84"), "receivers": {$elemMatch: {"address": "000000000020"}}}, {$set: {"receivers.$.status": "sending"}})> db.schedule.findOne(){"_id" : ObjectId("51e930f92291307bb05a1a84"),"direction" : 2,"messages" : ["m1","m2","m3"],"receivers" : [{"address" : "000000000020","status" : "sending"},{"address" : "000000000018","status" : "waiting"}],"speed" : 3,"start_time" : "1374236921","stay_time" : 1,"user_id" : ObjectId("518b7fc5117e87bce28f2444")}

$ 這是個預留位置,表示第一個被找到的數組元素。文檔:http://docs.mongodb.org/manual/core/update/#array

Name Description
$ Acts as a placeholder to update the first element that matches the query condition in an update.

C++代碼來了:

void SaveScheduleMessageStatus(string const& message_id, string const& address, string const& status) {  shared_ptr<MongoSession> mongo_session = MongoSessionFactory::GetSession();  BSONObjBuilder condition;  condition.append("_id", OID(message_id));  BSONObjBuilder con1;  con1.append("address", address);      BSONObjBuilder con2;  con2.append("$elemMatch", con1.obj());  condition.append("receivers", con2.obj());  BSONObjBuilder recs;  recs.append("receivers.$.status", status);  BSONObjBuilder set;  set.append("$set", recs.obj());      mongo_session->GetDBClientBase().update("db.schedule", mongo::Query(condition.obj()), set.obj());}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.