问题
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