在MongoDB中对内部项目进行数组索引或索引以获取值
首先,让我们创建一个包含文档的集合,并使用sureIndex()创建一个索引-
> db.demo323.insertOne({"details":{"Name":"Chris","Age":34}}); { "acknowledged" : true, "insertedId" : ObjectId("5e51157af8647eb59e56206e") } > db.demo323.insertOne({"details":{"Name":"David","Age":31}}); { "acknowledged" : true, "insertedId" : ObjectId("5e511581f8647eb59e56206f") } > db.demo323.insertOne({"details":{"Name":"Bob","Age":28}}); { "acknowledged" : true, "insertedId" : ObjectId("5e511589f8647eb59e562070") } > db.demo323.ensureIndex({"details.Name":1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo323.find();
这将产生以下输出-
{ "_id" : ObjectId("5e51157af8647eb59e56206e"), "details" : { "Name" : "Chris", "Age" : 34 } } { "_id" : ObjectId("5e511581f8647eb59e56206f"), "details" : { "Name" : "David", "Age" : 31 } } { "_id" : ObjectId("5e511589f8647eb59e562070"), "details" : { "Name" : "Bob", "Age" : 28 } }
以下是从数组中查找值的查询-
> db.demo323.find({"details.Name":"Bob"});
这将产生以下输出-
{ "_id" : ObjectId("5e511589f8647eb59e562070"), "details" : { "Name" : "Bob", "Age" : 28 } }