数组索引或索引 MongoDB 中的子项以获取值
首先,使用文档创建集合并使用 ensureIndex() 创建索引 −
> 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 } }
广告