是否包括所有现有字段并在MongoDB中添加新字段以记录文档?
您可以借助$addFields运算符来实现。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.addFieldDemo.insertOne({"EmployeeId":101,"EmployeeName":"Larry","EmployeeDetails":{"EmployeeSalary":65000,"EmployeeCity":"New York","Message":"Hi"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f654d8d10a061296a3c44")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.addFieldDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c7f654d8d10a061296a3c44"),
"EmployeeId" : 101,
"EmployeeName" : "Larry",
"EmployeeDetails" : {
"EmployeeSalary" : 65000,
"EmployeeCity" : "New York",
"Message" : "Hi"
}
}
这是包含所有现有字段并向MongoDB中的文档添加新字段的查询-
> db.addFieldDemo.aggregate([ { "$addFields": { "EmployeeBasicSalary":"$EmployeeDetails.EmployeeSalary" } } ]).pretty();
以下是输出-
{"_id" : ObjectId("5c7f654d8d10a061296a3c44"),
"EmployeeId" : 101,
"EmployeeName" : "Larry",
"EmployeeDetails" : {
"EmployeeSalary" : 65000,
"EmployeeCity" : "New York",
"Message" : "Hi"
},
"EmployeeBasicSalary" : 65000
}
查看示例输出,已添加“ EmployeeBasicSalary”。
以上是 是否包括所有现有字段并在MongoDB中添加新字段以记录文档? 的全部内容, 来源链接: utcz.com/z/351406.html