是的,您可以通过对索引进行索引(例如“ properties.k”作为键,将“ properties.v”作为值)来实现此目的。相同的用于在中实现ensureIndex()
。
让我们首先来看一个示例并创建包含文档的集合-
> db.demo274.insertOne({"details":[{StudentFirstName:"Chris",StudentLastName:"Brown"}, ... {StudentFirstName:"David",StudentLastName:"Miller"}, ... {StudentFirstName:"John",StudentLastName:"Smith"}, ... {StudentFirstName:"John",StudentLastName:"Doe"} ...] ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e48de35dd099650a5401a42") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo274.find().pretty();
输出结果
这将产生以下输出-
{ "_id" : ObjectId("5e48de35dd099650a5401a42"), "details" : [ { "StudentFirstName" : "Chris", "StudentLastName" : "Brown" }, { "StudentFirstName" : "David", "StudentLastName" : "Miller" }, { "StudentFirstName" : "John", "StudentLastName" : "Smith" }, { "StudentFirstName" : "John", "StudentLastName" : "Doe" } ] }
以下是在没有已知字段名称的情况下通过MongoDB子文档查询时利用索引的查询-
> db.demo274.ensureIndex({"details.StudentFirstName": 1, "details.StudentLastName": 1});
输出结果
这将产生以下输出-
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }