1

Is there a way to retrieve all the values of a fields type array

ie

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

the result should be like "android", "actionscript", "java","js", "php", "scala"

0

2 Answers 2

1

You can $unwind, and then $group them back

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

The result would be

{ _id: "android"},
{ _id: "actionscript"},
{ _id: "java"},
{ _id: "js"},
{ _id: "php"},
{ _id: "scala"}
Sign up to request clarification or add additional context in comments.

2 Comments

> db.posts.aggregate({ $unwind : "$tags" }, {$group:{_id: '$tag'}); ... I see only ...
FYI: You're missing a } at the end of the $group and you'd need to group on '$tags'.
0

Use the distinct command (reference):

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

You could use aggregation if you eventually needed something more complex:

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

Results:

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

I'd use $project (reference) to reduce the number of fields being passed through the pipeline though. In the example above, I've used $project to include only the tags for example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.