如何用数组中的多键索引改进MongoDB查询?
为此,请使用$elemMatch,该查询用于查询嵌套对象。让我们创建一个包含文档的集合-
> db.demo444.insertOne(
... {
... "Information": [{
... id:1,
... Name:"Chris"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:2,
... Name:"David"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:3,
... Name:"Bob"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo444.find();
这将产生以下输出-
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] }以下是使用数组中的多键索引改进查询的查询-
> db.demo444.find({
... "Information":{
... $elemMatch:{
... id:2,
... Name:"David"
... }
... }
... })这将产生以下输出-
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }热门推荐
10 新房开工吉日祝福语简短
11 九子订婚祝福语简短
12 简短大气的狗年祝福语
13 信耶稣的人祝福语简短
14 表达朋友的祝福语简短
15 父亲祝福语大全简短语
16 祝福语诗意文案简短
17 对疫情的简短祝福语
18 许嵩生日祝福语简短