使用MongoDB在整个阵列上进行多键索引?
首先让我们创建一个包含文档的集合-
> db.demo277.insertOne({"details":[{"FirstName":"John"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e48fb21dd099650a5401a52") } > db.demo277.insertOne({"details":[{"FirstName":"David"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e48fb27dd099650a5401a53") } > db.demo277.insertOne({"details":[{"FirstName":"Chris"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e48fb2bdd099650a5401a54") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo277.find();
这将产生以下输出-
{ "_id" : ObjectId("5e48fb21dd099650a5401a52"), "details" : [ { "FirstName" : "John" } ] } { "_id" : ObjectId("5e48fb27dd099650a5401a53"), "details" : [ { "FirstName" : "David" } ] } { "_id" : ObjectId("5e48fb2bdd099650a5401a54"), "details" : [ { "FirstName" : "Chris" } ] }
以下是在整个数组上实现多键索引的查询。它确实扫描完整的文档-
> db.demo277.find({"details":{FirstName:"David"}});
这将产生以下输出-
{ "_id" : ObjectId("5e48fb27dd099650a5401a53"), "details" : [ { "FirstName" : "David" } ] }