将有可能合计.我将对象的键更改为它的_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聚合
发布评论