如何优化 MongoDB 数组中多键索引的查询?
mongodbdatabasebig data analytics
为此,可以使用 `$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" } ] }

