5

I have my asset documents in the below format.

db.asset.find({}).limit(1).pretty()
{
    "_id" : ObjectId("54e650a10364a65f62c0df4a"),
    "_class" : "com.model.core.Asset",
    "displayName" : "Bingo Rhymes For Children + More 3D Animation Nursery Rhymes & Kids' Songs",
    "assetType" : "VIDEO",
    "active" : true,
    "originalUrl" : "https://www.youtube.com/watch?v=j-tdVvvXn9k&feature=youtube_gdata",
    "groupIds" : [ ],
    "folderIds" : [
        "54e6507b0364a65f62c0df47",
        "54e6507b0364a65f62c0df48"
    ]
}

As you can see each asset can have a collection of folderId to which it is associated with. If I want to find the folderIds along with the associated assets how does the mongo aggregate query will look like? Essentially I want to group the assets by folderId.

2
  • It is unclear what you are asking here. What are you trying to do? what is the expected result? Commented Oct 14, 2015 at 20:04
  • @user3100115 Essentially I want to group the assets by folderId. Commented Oct 14, 2015 at 20:19

1 Answer 1

7

You first need to unwind by the folderIds field, than group by _id and push the asset _id into a list assets_id.

db.asset.aggregate([{$unwind:"$folderIds"},  {$group:{_id: "$folderIds",assets:{$push: {assets_id:"$_id"}}}}])
Sign up to request clarification or add additional context in comments.

3 Comments

I think this gets me one-on-one association of the folderId vs assetId. Here is the results of the query you suggested. db.asset.aggregate([{$unwind:"$folderIds"}, {$group:{_id:{"folderIds":"$folderIds","asset_id":"$_id"}}}]) { "_id" : { "folderIds" : "54f8a2ed0364edbff0152df3", "asset_id" : ObjectId("55a53cfd93861c7d709af3c7") } } { "_id" : { "folderIds" : "54f8a2ed0364edbff0152df3", "asset_id" : ObjectId("552ff98d9386ca008fe2464c") } }. Can I get the assetIds grouped together for each folderId.
Thank you but the new query doesn't return any results.
Thank you. This works. db.asset.aggregate([{$unwind:"$folderIds"}, {$group:{_id: "$folderIds",assets:{$push: {assets_id:"$_id"}}}}])

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.