mongodb序列化子集结果



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

{ "_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.products.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"
    }
]

我需要用mongophp官方驱动程序来实现这个查询,但语言并不重要,我只想了解通过mongoshell 可以通过什么逻辑来实现这一点

tnk!

最简单的选择是使用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,
  }}
)

相关内容

最新更新