查询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" }
以上是 查询MongoDB以进行嵌套搜索 的全部内容, 来源链接: utcz.com/z/347225.html