【问题标题】:Processing array of generic BSON documents with MongoDB C++ driver使用 MongoDB C++ 驱动程序处理通用 BSON 文档数组
【发布时间】:2013-02-12 22:28:38
【问题描述】:

我的 MongoDB 测试数据库中有以下文档:

> db.a.find().pretty()
{
    "_id" : ObjectId("5113d680732fb764c4464fdf"),
    "x" : [
            {
                "a" : 1,
                "b" : 2
            },
            {
                "a" : 3,
                "b" : 4
            }
          ]
}

我正在尝试访问和处理“x”数组中的元素。但是,Mongo 驱动程序似乎不是将其识别为 JSON 文档数组,而是将其识别为 Date 类型,如下代码所示:

auto_ptr<DBClientCursor> cursor = c.query("test.a", BSONObj());
while (cursor->more()) {      
  BSONObj r = cursor->next();
  cout << r.toString() << std::endl;
}

哪个输出是:

{ _id: ObjectId('51138456732fb764c4464fde'), x: new Date(1360233558334) }

我正在尝试遵循http://api.mongodb.org/cplusplushttp://docs.mongodb.org/ecosystem/drivers/cpp-bson-array-examples/ 中的文档,但效果很差。我发现了处理数组的其他示例,但总是使用简单类型(例如整数数组),但当数组中的元素本身是 BSON 文档时则不然。

请问您有一些处理数组的代码示例,哪些元素是通用 BSON 元素?

【问题讨论】:

  • 而且,mongo shell 和 trace 显示的 ObjectID 似乎不一样。很奇怪……

标签: c++ arrays mongodb bson


【解决方案1】:

您可以使用 .Array() 方法或 getFieldDotted() 方法:如下所示:

Query query = Query();
auto_ptr<DBClientCursor> cursor = myConn.query("test.a", query);

while( cursor->more() ) {
    BSONObj nextObject = cursor->next();

    cout << nextObject["x"].Array()[0]["a"] << endl;
    cout << nextObject.getFieldDotted("x.0.a") << endl;


}

【讨论】:

  • 我终于找到了解决办法,不过还是谢谢你的提示!我不知道这种情况下的 [ ] 表示法和 getFieldDotted() 方法。
【解决方案2】:

最后,embeddedObject() 方法似乎是关键:

auto_ptr<DBClientCursor> cursor = c.query("test.a", BSONObj());
while (cursor->more()) { 
  BSONObj r = cursor->next();
  cout << "Processing JSON document: " << r.toString() << std::endl;
  std::vector<BSONElement> be = r.getField("x").Array();
  for (unsigned int i = 0; i<be.size(); i++) {
      cout << "Processing array element: " << be[i].toString() << std::endl;
      cout << "                 of type: " << be[i].type() << std::endl;
      BSONObj bo = be[i].embeddedObject();
      cout << "Processing a field: " << bo.getField("a").toString() << std::endl;
      cout << "Processing b field: " << bo.getField("b").toString() << std::endl;
  }
 }

我错误地检索了不同的 ObjectID 和不同的类型(日期而不是数组),因为我正在寻找不同的集合:$

抱歉打扰了。我希望上面的片段可以帮助其他人弄清楚如何使用 MongoDB C++ 驱动程序来操作数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多