获取唯一的子子文档

时间:2014-03-22 09:00:21

标签: mongodb mongoose

我有这样的文件集合:

{
  "_id" : ObjectId("532d4e7d569c9e4574d5156e"),
  "title" : "Book Title"
  "author" : "Book Author",
  "owner" : "532d4e7c569c9e4574d51568",
  "pages" : [
    {
      "texts" : [
        {
          "_id" : ObjectId("532d4e7d569c9e4574d51572"),
          "paragraphs" : [ ],
          "format" : [ ],
          "position" : {
            "y" : 0,
            "x" : 0
          }
        }
      ],
      "images" : [
        {
          "_id" : ObjectId("532d4e7f569c9e4574d51573"),
          "position" : {
            "y" : 0,
            "x" : 0
          }
        }
      ],
    },
    {
      "_id" : ObjectId("532d4e7d569c9e4574d51571"),
      "videos" : [ ],
      "audios" : [ ],
      "images" : [ ],
      "texts" : [ ],
      "animations" : [ ]
    }
  ]
}

我想获得text唯一的_id子文档:

db.projects.find({'pages.texts._id': ObjectId("532d4e7d569c9e4574d51572")}, {'pages.$.texts.$': 1}).pretty()

但它不起作用。

我只想获得这部分文件:

{
  "_id" : ObjectId("532d4e7d569c9e4574d51572"),
  "paragraphs" : [ ],
  "format" : [ ],
  "position" : {
    "y" : 0,
    "x" : 0
  }
}

1 个答案:

答案 0 :(得分:1)

来自positional $运营商的文档:

  

位置$运算符限制查询结果中包含的字段的内容,以包含第一个匹配元素。要指定要更新的数组元素,请参阅位置$运算符以获取更新。

您有两个数组。 首先pages第二texts

"位置"在第一个数组上匹配,而不是再次匹配。你可以做  这与.aggregate()

Projects.aggregate([
       // Match documents
       { "$match": {
           "pages.texts._id": ObjectId("532d4e7d569c9e4574d51572")
       }},

       // Unwind the pages array
       { "$unwind": "$pages" },

       // Unwind the "texts" array
       { "$unwind": "$pages.texts" },

       // Filter array
       { "$match": {
           "pages.texts._id": ObjectId("532d4e7d569c9e4574d51572")
       }},

       // Re-form
       { "$group": {
           "_id": "$_id",
           "texts": { "$push": "$pages.texts"  }
       }}
    ],
    function(err, res) {
       // do things with res or err here
})

mongoose documentation

更多关于aggregation operators

更多阅读here