更改关键文档mongodb聚合

编程入门 行业动态 更新时间:2024-10-25 18:35:31
本文介绍了更改关键文档mongodb聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

将有可能合计.我将对象的键更改为它的_id.我正在尝试将map-reduce与项目聚合在一起.任何的想法? 我所拥有的:

would be possible with an aggregate. I change the key of the object to the _id of it. I'm trying to do with map-reduce in aggregation with project. Any idea? what I have:

{"serie" : { "_id" : ObjectId("5a55f988b6c9dd15b47faa2a"), "updatedAt" : ISODate("2018-02-09T13:22:54.521Z"), "createdAt" : ISODate("2018-01-10T11:31:20.978Z"), "deletar" : false, "infantil" : false, "status" : true, "turma" : [], }}

我要如何离开:

{"5a55f988b6c9dd15b47faa2a" : { "updatedAt" : ISODate("2018-02-09T13:22:54.521Z"), "createdAt" : ISODate("2018-01-10T11:31:20.978Z"), "deletar" : false, "infantil" : false, "status" : true, "turma" : [] }}

推荐答案

要使用动态键创建嵌套对象,您需要使用 $ arrayToObject ,它将键(k)和values(v)的数组作为参数.然后,您可以使用 $ replaceRoot 来推广新的反对根级.您需要MongoDB 4.0使用将ObjectId转换为string $ toString 运算符

To create a nested object with dynamic key you need to use $arrayToObject which takes an array of keys (k) and values (v) as a parameter. Then you can use $replaceRoot to promote that new object to a root level. You need MongoDB 4.0 to convert ObjectId to string using $toString operator

db.col.aggregate([ { $replaceRoot: { newRoot: { $arrayToObject: { $let: { vars: { data: [ { k: { $toString: "$_id" }, v: "$serie" } ] }, in: "$$data" } } } } } ])

输出:

{ "5b97f6cea37f8c96db70fea9" : { "_id" : ObjectId("5a55f988b6c9dd15b47faa2a"), "updatedAt" : ISODate("2018-02-09T13:22:54.521Z"), "createdAt" : ISODate("2018-01-10T11:31:20.978Z"), "deletar" : false, "infantil" : false, "status" : true, "turma" : [ ] } }

如果要在结果中去除_id,则可以在v中显式指定字段,例如:

If you want to get rid of _id in your result you can specify fields explicitly in v like:

v: { updatedAt: "$serie.updatedAt", createdAt: "$serie.createdAt", ... }

更多推荐

更改关键文档mongodb聚合

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

发布评论

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

>www.elefans.com

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