1

无法理解查询此 mongo 文档的特定语法。我只想获得(项目?)u =“123”的“条目”。我尝试过这样的事情:

db["conv_msgs_822"].aggregate({$match: {"_id": "1234", "entries.$.u" : "123"}})

哪个失败了。这甚至可能吗?

{
  "_id" : "1234",
  "entries" : {
    "1" : {
      "body" : "aesf asdf asdf asdf asdf",
      "u" : "123"
    },
    "2" : {
      "body" : "1234",
      "u" : ""
    },
    "3" : {
      "body" : "some other body ",
      "u" : "14"
    },
    "4" : {
      "body" : "another body",
      "u" : "123"
    }
  }
}
4

2 回答 2

3

对于您当前的文档结构,这确实是不可能的。您确实需要将这些子文档放在一个数组中才能执行此类操作。

假设您重组了文档以匹配此内容(如果需要,您甚至可以将索引作为字段添加回子文档中):

{
  "_id" : "1234",
  "entries" : [
    {
      "body" : "aesf asdf asdf asdf asdf",
      "u" : "123"
    },
    {
      "body" : "1234",
      "u" : ""
    },
    {
      "body" : "some other body ",
      "u" : "14"
    },
    {
      "body" : "another body",
      "u" : "123"
    }
  ]
}

然后,您可以使用带有$运算符的基本查询作为投影来仅匹配第一项。

> db.conv_msgs_822.find({"_id": "1234", "entries.u": "123"}, {"entries.$": 1})

这将产生:

{ "_id" : "1234", "entries" : [ { "body" : "aesf asdf asdf asdf asdf", "u" : "123" } ] }

要匹配您需要聚合的所有项目,$unwind它们$match是子元素,然后$group它们返回。

db.conv_msgs_822.aggregate(
  {$match: {"_id": "1234", "entries.u": "123"}},
  {$unwind: "$entries"},
  {$match: {"entries.u": "123"}},
  {$group: {_id: "$_id", entries: {$push: "$entries"}}}
)

导致:

{
    "result" : [
        {
            "_id" : "1234",
            "entries" : [
                {
                    "body" : "aesf asdf asdf asdf asdf",
                    "u" : "123"
                },
                {
                    "body" : "another body",
                    "u" : "123"
                }
            ]
        }
    ],
    "ok" : 1
}

我希望这会有所帮助。

于 2013-08-19T21:43:16.727 回答
0

到目前为止,对我来说最大的潜力是:

db.eval( function(doc, u_val) {
            var msgs = doc["entries"];
            var cleaned_entries = {};
              for (var k in entries){
                if (msgs[k].u == u_val){
                  cleaned_entries[k] = entries[k];
                  }
              };
            doc["entries"] = cleaned_entries

            return doc
         },
         db["conv_msgs_822"].findOne({"_id": "1234"}), 123 );
于 2013-08-20T06:35:13.900 回答