在 MongoDB 中插入所有现有字段并向文档中添加新的字段?
借助 $addFields 运算符,可以实现这一点。为了理解该概念,让我们使用该文档创建一个集合。创建包含文档的集合的查询如下 −
> db.addFieldDemo.insertOne({"EmployeeId":101,"EmployeeName":"Larry","EmployeeDetails":{ "EmployeeSalary":65000,"EmployeeCity":"New York","Message":"Hi"}}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f654d8d10a061296a3c44") }
借助 find() 方法从集合中显示所有文档。查询如下 −
> 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”。
广告