如何在MongoDB中将数组字段的元素更改为具有单个属性的字典的值 [英] How to change elements of an array field to values of a dict with a single attribute in MongoDB
本文介绍了如何在MongoDB中将数组字段的元素更改为具有单个属性的字典的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种将数组字段的元素更改为具有单个属性的字典值的方法.我不必将结果写回到表中.我只需要那样阅读即可.
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}
换句话说, b
的每个元素变成具有单个属性 foo
的字典.
In other words, each element of b
becomes a dict with a single attribute, foo
.
这就像是 $ project
或 $ replaceRoot
或 $ set
的工作.
我正在Ubuntu 18.04上使用MongoDB 4.2.2和PyMongo 3.10.1.
I'm using MongoDB 4.2.2 and PyMongo 3.10.1 on Ubuntu 18.04.
推荐答案
您可以使用聚合:
db.collection.aggregate([{$addFields : {b : { $map: { input: '$b', in: {foo : '$$this'} } }}}])
参考: $ addFields, $ map
这篇关于如何在MongoDB中将数组字段的元素更改为具有单个属性的字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文