与$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" } }