对于新字段,请在MongoDB中使用$addFields。$addFields用于向文档添加新字段。让我们创建一个包含文档的集合-
> db.demo429.insertOne( ... { ... "_id": 101, ... "Value": 3, ... "details": [ ... { ... "Age": 29, ... "Value": 3, ... "details1": [ ... 1, ... 2, ... 3 ... ] ... }, ... { ... "Age": 31, ... "Value": 4, ... "details1": [ ... 354 ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo429.find();
这将产生以下输出-
{ "_id" : 101, "Value" : 3, "details" : [ { "Age" : 29, "Value" : 3, "details1" : [ 1, 2, 3 ] }, { "Age" : 31, "Value" : 4, "details1" : [ 354 ] } ] }
以下是创建新字段并设置其他字段的计数的查询-
> db.demo429.aggregate([ ... { ... "$addFields": { ... "details" : { ... "$map": { ... "input": "$details", ... "as": "d", ... "in": { ... "Age" : "$$d.Age", ... "NumberOfDetails1": { "$size": "$$d.details1" } ... } ... } ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : 101, "Value" : 3, "details" : [ { "Age" : 29, "NumberOfDetails1" : 3 }, { "Age" : 31, "NumberOfDetails1" : 1 } ] }