有没有办法检索所有值 字段类型数组
即
{ "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”
答案 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"
}
]
我会使用$project
(reference)来减少通过管道传递的字段数。在上面的示例中,我使用$project
仅包含tags
。