在 MongoDB 中查询嵌套搜索


对于嵌套搜索,使用 $and 和 $or。我们首先创建一个带文档的集合 −

> db.demo12.insertOne({"Name":"Chris","Age":23,"CountryName":"US","Message":"Hello"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70a2d7df943a7cec4fa2")
}
> db.demo12.insertOne({"Name":"David","Age":21,"CountryName":"US","Message":"Hello"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70acd7df943a7cec4fa3")
}
> db.demo12.insertOne({"Name":"Bob","Age":23,"CountryName":"AUS","Message":"Hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70bad7df943a7cec4fa4")
}
> db.demo12.insertOne({"Name":"Carol","Age":24,"CountryName":"US","Message":"Hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f70c7d7df943a7cec4fa5")
}

下面是使用 find() 方法从集合中显示所有文档的查询 −

> db.demo12.find();

这将产生以下输出 −

{ "_id" : ObjectId("5e0f70a2d7df943a7cec4fa2"), "Name" : "Chris", "Age" : 23, "CountryName" : "US", "Message" : "Hello" }
{ "_id" : ObjectId("5e0f70acd7df943a7cec4fa3"), "Name" : "David", "Age" : 21, "CountryName" : "US", "Message" : "Hello" }
{ "_id" : ObjectId("5e0f70bad7df943a7cec4fa4"), "Name" : "Bob", "Age" : 23, "CountryName" : "AUS", "Message" : "Hi" }
{ "_id" : ObjectId("5e0f70c7d7df943a7cec4fa5"), "Name" : "Carol", "Age" : 24, "CountryName" : "US", "Message" : "Hi" }

以下是 MongoDB 嵌套搜索的查询 −

> db.demo12.find({ $and : [ { Name : 'Bob' }, { Age : 23 }, { $or : [ { CountryName : 'UK' }, { Message : 'Hi' } ] } ] } );

这将产生以下输出 −

{ "_id" : ObjectId("5e0f70bad7df943a7cec4fa4"), "Name" : "Bob", "Age" : 23, "CountryName" : "AUS", "Message" : "Hi" }

更新于: 2020 年 4 月 1 日

184 次观看

开启您的 职业生涯

完成课程并获得认证

开始
广告