mongodb如何检索字段类型数组中的所有值?

时间:2014-01-26 18:38:27

标签: mongodb

有没有办法检索所有值 字段类型数组

{ "slug" : "my-post", "status" : "publish", "published" : ISODate("2014-01-26T18:28:11Z"), "title" : "my post", "body" : "my body post", "_id" : ObjectId("52e553c937fb8bf218b8c624"), "tags" : [  "js",  "php",  "scala" ], "created" : ISODate("2014-01-26T18:28:25.298Z"), "author" : "whisher", "__v" : 0 }
{ "slug" : "my-post-2", "status" : "publish", "published" : ISODate("2014-01-26T18:28:27Z"), "title" : "my post 2", "body" : "spost body", "_id" : ObjectId("52e5540837fb8bf218b8c625"), "tags" : [  "android",  "actionscript",  "java" ], "created" : ISODate("2014-01-26T18:29:28.915Z"), "author" : "whisher", "__v" : 0 }

结果应该是这样的 “android”,“actionscript”,“java”,“js”,“php”,“scala”

2 个答案:

答案 0 :(得分:1)

您可以$unwind,然后$group他们回来

db.collection.aggregate({ $unwind : "$tags" }, {$group:{_id: "$tags"}});

结果将是

{ _id: "android"},
{ _id: "actionscript"},
{ _id: "java"},
{ _id: "js"},
{ _id: "php"},
{ _id: "scala"}

答案 1 :(得分:0)

使用distinct命令(reference):

> db.test.distinct("tags")
[ "js", "php", "scala", "actionscript", "android", "java" ]

如果你最终需要更复杂的东西,你可以使用聚合:

> db.test.aggregate(
         { $project: { tags : 1 } },  
         { $unwind : "$tags" }, 
         { $group : { _id: "$tags" }  }  );

结果:

[
    {
            "_id" : "java"
    },
    {
            "_id" : "actionscript"
    },
    {
            "_id" : "android"
    },
    {
            "_id" : "scala"
    },
    {
            "_id" : "php"
    },
    {
            "_id" : "js"
    }
]

我会使用$projectreference)来减少通过管道传递的字段数。在上面的示例中,我使用$project仅包含tags