MongoDB 聚合查询

编程入门 行业动态 更新时间:2024-10-21 12:40:49
本文介绍了MongoDB 聚合查询 - 重命名从嵌入文档中返回的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用聚合运算符来返回具有嵌入(子)文档数组的文档.我想重命名数组的字段名称,并重命名数组嵌入文档中的字段名称.

例如,对于投影,我想将数组从friends"重命名为buddies",并且我还想将嵌入文档中的字段从name"重命名为nickName".我可以在聚合操作中执行此操作吗?如果可以,如何执行?

以下是源文档的示例:

[{_id:对象ID,name: '马修',朋友们: [{名称:'苗条',年龄:'32'},{名称:'布巴',年龄:'36'}]}]

结果应该是这样的:

[{_id:对象ID,name: '马修',小伙伴:【{昵称:'克里斯',年龄:'32'},{昵称:'吉姆',年龄:'36'}]}]

提前感谢您的帮助.

解决方案

对此有几种方法,但这在很大程度上取决于您的 MongoDB 版本.2.6 及更高版本的更新版本支持 $map 运算符,您可以在 $project 做你想做的事:

db.friend.aggregate([{$项目":{名称":1,伙伴":{$地图":{"input": "$friends","as": "el",在": {"nickName": "$$el.name","age": "$$el.age"}}}}}])

在以前的版本中,您将使用 $unwind 处理数组元素并通过 $group:

db.collection.aggregate([{ "$unwind": "$friends" },{$组":{"_id": "$_id","name": { "$first": "$name" },伙伴":{$push":{"nickName": "$friends.name","age": "$friends.age"}}}}])

第一种形式的效率更高一些,因为您不会对数组内容进行反规范化并在管道中生成更多要处理的文档.

I'm currently using aggregate operator to return documents that has an array of embedded (sub) documents. I want to rename the field name for the array and also rename fields names in the embedded documents of the array.

As an example, for projection I want to rename the array from "friends" to "buddies" and I also want to rename fields in the embedded document from "name" to "nickName". Can I do this within an aggregate operation and if so how?

Here's an example of the source document:

[ { _id: ObjectID, name: 'Matthew', friends: [ {name: 'Slim', age: '32'}, {name: 'buba', age: '36'} ] } ]

Here's what the results should look like:

[ { _id: ObjectID, name: 'Matthew', buddies: [ {nickName: 'Chris', age: '32'}, {nickName: 'Jim', age: '36'} ] } ]

Thanks for the help in advance.

解决方案

There are a couple of approaches to this, but it largely depends on your MongoDB version. More recent versions from 2.6 and upwards support the $map operator which you can use in $project to do what you want:

db.friend.aggregate([ { "$project": { "name": 1, "buddies": { "$map": { "input": "$friends", "as": "el", "in": { "nickName": "$$el.name", "age": "$$el.age" } } } }} ])

In prior versions you would use $unwind to work with the array elements and re-construct via $group:

db.collection.aggregate([ { "$unwind": "$friends" }, { "$group": { "_id": "$_id", "name": { "$first": "$name" }, "buddies": { "$push": { "nickName": "$friends.name", "age": "$friends.age" } } }} ])

With the first form being a little more efficient as you are not de-normalizing the array content and producing more documents in the pipeline to process.

更多推荐

MongoDB 聚合查询

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

发布评论

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

>www.elefans.com

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