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"
            }
        ]
    }
]

しかし、次のような(または同様の)単純な1次元配列を取得したい:

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

このクエリをmongo php公式ドライバーで実装する必要がありますが、言語は重要ではありません。mongoシェルでこれを達成できるロジックを理解したいだけです

tnk!

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 に答える