MongoDB查询以查找具有特定名字和姓氏的文档
要查找具有特定名字和姓氏的文档,请使用$and和$in。在MongoDB中实现find()
。让我们创建一个包含文档的集合-
> db.demo692.insertOne({FirstName:"Chris","LastName":"Brown"});{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585dca7e81adc6a0b396a")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585e2a7e81adc6a0b396b")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585e7a7e81adc6a0b396c")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585efa7e81adc6a0b396d")
}
> db.demo692.insertOne({FirstName:"Adam","LastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585faa7e81adc6a0b396e")
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo692.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5ea585efa7e81adc6a0b396d"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5ea585faa7e81adc6a0b396e"), "FirstName" : "Adam", "LastName" : "Smith" }
以下是查询以查找具有特定名字和姓氏的文档-
> db.demo692.find({$and:[ {FirstName: {$in: ["Chris", "John"]}},... {LastName:{$in:["Brown", "Smith"]}}
... ]
... }
... );
这将产生以下输出-
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
以上是 MongoDB查询以查找具有特定名字和姓氏的文档 的全部内容, 来源链接: utcz.com/z/326831.html