mongodb序列化子集结果

标签 mongodb mongodb-php

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

{ "_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通过什么逻辑可以完成这个

天啊!

最佳答案

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

关于mongodb序列化子集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11770590/

相关文章:

node.js - mongodb 匹配和组 2 查询合二为一

node.js - 如何解决 NodeJS 和 MongoDB 中的这种(IMO)意外行为

php - Mongodb php查询,在数组中搜索?

php - 如何将 maxPoolSize 与 mongodb-php 驱动程序版本 1.2.0 一起使用

php - Laravel:无法对​​有效负载进行 JSON 编码。错误代码:5

php - MongoDB 更改文档中数组的顺序

MongoDB 2.6索引设置,使用$ or,$ in进行查询,并带有限制和排序

javascript - 异步 Angular/Node $scope 调用

java - Vava 查询 MongoDB : find event in a specific date range

php json_encode 不会产生真实对象/将数组字符串转换为真实对象/将 php 数组转换为 json