您可以将$literal运算符与聚合框架一起使用。首先让我们创建一个包含文档的集合-
> db.fieldWithStaticValue.insertOne({"Name":"Larry","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6554c7924bb85b3f48948") } > db.fieldWithStaticValue.insertOne({"Name":"Chris","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd655567924bb85b3f48949") } > db.fieldWithStaticValue.insertOne({"Name":"David","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd655607924bb85b3f4894a") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.fieldWithStaticValue.find();
这将产生以下输出-
{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24 } { "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23 } { "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26 }
以下是使用$literal将具有静态值的字段添加到MongoDB的查询-
> db.fieldWithStaticValue.aggregate( [ { $project: { Name: 1,Age:1, "StaticValue": { $literal: 100 } } } ]);
这将产生以下输出-
{ "_id" : ObjectId("5cd6554c7924bb85b3f48948"), "Name" : "Larry", "Age" : 24, "StaticValue" : 100 } { "_id" : ObjectId("5cd655567924bb85b3f48949"), "Name" : "Chris", "Age" : 23, "StaticValue" : 100 } { "_id" : ObjectId("5cd655607924bb85b3f4894a"), "Name" : "David", "Age" : 26, "StaticValue" : 100 }