如何在 MongoDB 查询中使用变量
要使用变量,可在 MongoDB 中使用 var。我们创建一个包含文档的集合:
> db.demo107.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2ee1b19fd5fd66da214471")
}
> db.demo107.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2ee1b49fd5fd66da214472")
}
> db.demo107.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2ee1b89fd5fd66da214473")
}使用 find() 方法从集合显示所有文档:
> db.demo107.find();
这将产生以下输出:
{ "_id" : ObjectId("5e2ee1b19fd5fd66da214471"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2ee1b49fd5fd66da214472"), "Name" : "Bob" }
{ "_id" : ObjectId("5e2ee1b89fd5fd66da214473"), "Name" : "David" }以下是 MongoDB 中使用变量的查询:
> var firstName="Bob";
> db.demo107.find({"Name":firstName});这将产生以下输出:
{ "_id" : ObjectId("5e2ee1b49fd5fd66da214472"), "Name" : "Bob" }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP