MongoDB按数组字段中的值分组

编程入门 行业动态 更新时间:2024-10-16 02:29:19
本文介绍了MongoDB按数组字段中的值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的资产文件采用以下格式.

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" : "www.youtube/watch?v=j-tdVvvXn9k&feature=youtube_gdata", "groupIds" : [ ], "folderIds" : [ "54e6507b0364a65f62c0df47", "54e6507b0364a65f62c0df48" ] }

如您所见,每个资产都可以具有与其关联的folderId的集合.如果我想与相关资产一起找到folderIds,mongo聚合查询将如何显示?本质上,我想按folderId对资产进行分组.

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.

推荐答案

首先,您需要按folderIds字段展开,而不是按_id分组,然后将资产_id推送到列表assets_id中. /p>

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

更多推荐

MongoDB按数组字段中的值分组

本文发布于:2023-11-22 14:25:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617801.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字段   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!