3

我有这个简单的数据库,其中包含元素子集:

{ "_id" : ObjectId("5019eb2356d80cd005000000"),
    "photo" : "/pub/photos/file1.jpg",
    "comments" : [
        {
            "name" : "mike",
            "message" : "hello to all"
        },
        {
            "name" : "pedro",
            "message" : "hola a todos"
        }
    ]
},
{ "_id" : ObjectId("5019eb4756d80cd005000001"),
    "photo" : "/pub/photos/file2.jpg",
    "comments" : [
        {
            "name" : "luca",
            "message" : "ciao a tutti"
        },
        {
            "name" : "stef",
            "message" : "todos bien"
        },
        {
            "name" : "joice",
            "message" : "vamos a las playa"
        }
    ]
}

当我执行子集查找时: db.photos.find({},{"comments.name":1})

我收到这个结构:

[
    {
        "_id" : ObjectId("5019eb2356d80cd005000000"),
        "comments" : [
            {
                "name" : "mike"
            },
            {
                "name" : "pedro"
            }
        ]
    },
    {
        "_id" : ObjectId("5019eb4756d80cd005000001"),
        "comments" : [
            {
                "name" : "luca"
            },
            {
                "name" : "stef"
            },
            {
                "name" : "joice"
            }
        ]
    }
]

但我想得到一个简单的一维数组,像这样(或类似的):

[
    {
        "name" : "mike"
    },
    {
        "name" : "pedro"
    },
    {
        "name" : "luca"
    },
    {
        "name" : "stef"
    },
    {
        "name" : "joice"
    }
]

我需要用mongo php官方驱动来实现这个查询,但是语言并不重要,我只是想了解通过mongo shell可以通过什么逻辑来完成这个

天呐!

4

1 回答 1

3

最简单的选择是使用distinct()

>db.photos.distinct("comments.name");
[ "mike", "pedro", "joice", "luca", "stef" ]

这是另一个使用 JavaScript 的示例:

// Array to save results
> var names = []

// Find comments and save names
> db.photos.find({},{"comments.name":1}).forEach(
          function(doc) { doc.comments.forEach(
              function(comment) {names.push(comment.name)})
          })

// Check the results
> names
[ "mike", "pedro", "luca", "stef", "joice" ]

以下是在即将推出的 MongoDB 2.2 中使用新聚合框架的示例:

db.photos.aggregate(
  { $unwind : "$comments" },
  { $group : {
     _id: "names",
     names: { $addToSet : "$comments.name" }
  }},
  { $project : {
     '_id' : 0,
     'names' : 1,
  }}
)
于 2012-08-02T05:30:42.577 回答