在mongo中将多个子文档合并为一个新文档

编程入门 行业动态 更新时间:2024-10-27 18:17:52
本文介绍了在mongo中将多个子文档合并为一个新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在MongoDB中查询多个子文档并作为一个文档返回. 我认为聚合框架是必经之路,但看不到完全正确.

I am trying to query multiple sub-documents in MongoDB and return as a single doc. I think the aggregation framework is the way to go, but, can't see to get it exactly right.

使用以下文档:

{ "board_id": "1", "hosts": [{ "name": "bob", "ip": "10.1.2.3" }, { "name": "tom", "ip": "10.1.2.4" }] } { "board_id": "2", "hosts": [{ "name": "mickey", "ip": "10.2.2.3" }, { "name": "mouse", "ip": "10.2.2.4" }] } { "board_id": "3", "hosts": [{ "name": "pavel", "ip": "10.3.2.3" }, { "name": "kenrick", "ip": "10.3.2.4" }] }

试图获得这样的查询结果:

Trying to get a query result like this:

{ "hosts": [{ "name": "bob", "ip": "10.1.2.3" }, { "name": "tom", "ip": "10.1.2.4" }, { "name": "mickey", "ip": "10.2.2.3" }, { "name": "mouse", "ip": "10.2.2.4" }, { "name": "pavel", "ip": "10.3.2.3" }, { "name": "kenrick", "ip": "10.3.2.4" }] }

我已经尝试过了:

db.collection.aggregate([ { $unwind: '$hosts' }, { $project : { name: 1, hosts: 1, _id: 0 }} ])

但这不是我想要的.

推荐答案

您绝对可以使用聚合来做到这一点.假设您的数据位于名为board的集合中,那么请使用您的集合名称替换它.

You can definitely do this with aggregate. Let's assume your data is in collection named board, so please replace it with whatever your collection name is.

db.board.aggregate([ {$unwind:"$hosts"}, {$group:{_id:null, hosts:{$addToSet:"$hosts"}}}, {$project:{_id:0, hosts:1}} ]).pretty()

它将返回

{ "hosts" : [ { "name" : "kenrick", "ip" : "10.3.2.4" }, { "name" : "pavel", "ip" : "10.3.2.3" }, { "name" : "mouse", "ip" : "10.2.2.4" }, { "name" : "mickey", "ip" : "10.2.2.3" }, { "name" : "tom", "ip" : "10.1.2.4" }, { "name" : "bob", "ip" : "10.1.2.3" } ] }

更多推荐

在mongo中将多个子文档合并为一个新文档

本文发布于:2023-10-19 14:27:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507796.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   多个   并为   中将   mongo

发布评论

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

>www.elefans.com

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