How to change elements of an array field to values of a dict with a single attribute in MongoDB

荒凉一梦 提交于 2021-02-11 09:11:09

问题


I need a way to change the elements of an array field to values of a dict with a single attribute. I don't have to write the result back into my table. I just have to read it that way.

My table has rows like this :

{a: 1, b:[ {...}, ..., {...} ], c: 2}

I need a query that returns each row rewritten like this :

{a: 1, b: [ {foo: { ... }}, ..., {foo: {...}} ], c: 2}

In other words, each element of b becomes a dict with a single attribute, foo.

This feels like a job for $project or $replaceRoot or $set.

I'm using MongoDB 4.2.2 and PyMongo 3.10.1 on Ubuntu 18.04.


回答1:


You can do that using aggregation :

db.collection.aggregate([{$addFields : {b : { $map: { input: '$b', in: {foo : '$$this'} } }}}])

Test : MongoDB-Playground

Ref : $addFields , $map



来源:https://stackoverflow.com/questions/60173702/how-to-change-elements-of-an-array-field-to-values-of-a-dict-with-a-single-attri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!