使用聚合的 MongoDB 查询来替换值?
使用聚合框架和 $literal 操作符。我们首先使用文档创建一个集合 -
> db.replaceValueDemo.insertOne( { _id : 100, "EmployeeName" :"Chris", "EmployeeOtherDetails": { "EmployeeDesignation" : "HR", "EmployeeAge":27 } } ); { "acknowledged" : true, "insertedId" : 100 } > db.replaceValueDemo.insertOne( { _id : 101, "EmployeeName" :"David", "EmployeeOtherDetails": { "EmployeeDesignation" : "Tester", "EmployeeAge":26 } } ); { "acknowledged" : true, "insertedId" : 101 }
以下是使用 find() 方法显示集合中所有文档的查询 -
> db.replaceValueDemo.find().pretty();
这将产生以下输出 -
{ "_id" : 100, "EmployeeName" : "Chris", "EmployeeOtherDetails" : { "EmployeeDesignation" : "HR", "EmployeeAge" : 27 } } { "_id" : 101, "EmployeeName" : "David", "EmployeeOtherDetails" : { "EmployeeDesignation" : "Tester", "EmployeeAge" : 26 } }
以下是替换值的方法 -
> db.replaceValueDemo.aggregate([{ "$project": { "_id": 1, "EmployeeOtherDetails": { EmployeeAge: 1, EmployeeDesignation : { $literal: "Developer" } } } }]);
这将产生以下输出 -
{ "_id" : 100, "EmployeeOtherDetails" : { "EmployeeAge" : 27, "EmployeeDesignation" : "Developer" } } { "_id" : 101, "EmployeeOtherDetails" : { "EmployeeAge" : 26, "EmployeeDesignation" : "Developer" } }
广告