如何在数组中使用多键索引提高 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" } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP