对于用户定义的变量,请在MongoDB中使用var关键字。让我们创建一个包含文档的集合-
> db.demo327.insertOne({"FirstName":"Chris","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516952f8647eb59e562076") } > db.demo327.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e51695af8647eb59e562077") } > db.demo327.insertOne({"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516962f8647eb59e562078") } > db.demo327.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516968f8647eb59e562079") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo327.find();
这将产生以下输出-
{ "_id" : ObjectId("5e516952f8647eb59e562076"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5e51695af8647eb59e562077"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" }
以下是如何在查询中设置用户定义的变量-
> var name="John"; > db.demo327.find({"FirstName":name});
这将产生以下输出-
{ "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" }