在嵌套的MongoDB字段上创建索引?

您可以为此使用dot(。)表示法。首先让我们创建一个包含文档的集合-

> db.createIndexOnNestedFieldDemo.insertOne(
   {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"John","UserLastName":"Smith"}}});
   {
      "acknowledged" : true,
      "insertedId" : ObjectId("5ce929c778f00858fb12e916")
   }
>
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"Chris","UserLastName":"Brown"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929d678f00858fb12e917")
}
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"David","UserLastName":"Miller"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929e378f00858fb12e918")
}

以下是在find()方法的帮助下显示集合中所有文档的查询-

> db.createIndexOnNestedFieldDemo.find().pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5ce929c778f00858fb12e916"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "John",
         "UserLastName" : "Smith"
      }
   }
}
{
   "_id" : ObjectId("5ce929d678f00858fb12e917"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "Chris",
         "UserLastName" : "Brown"
      }
   }
}
{
   "_id" : ObjectId("5ce929e378f00858fb12e918"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "David",
         "UserLastName" : "Miller"
      }
   }
}

以下是在嵌套字段上创建索引的查询-

>db.createIndexOnNestedFieldDemo.createIndex({"UserDetails.UserPersonalDetails.UserLastName":1});

这将产生以下输出-

{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}