如何在 MongoDB 查询中添加一个具有静态值的字段?
你可以将 $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 }
广告