首页 文章资讯内容详情

如何用数组中的多键索引改进MongoDB查询?

2026-06-04 1 花语

为此,请使用$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" } ] }