Computer >> Computer tutorials >  >> Programming >> MongoDB

Can I utilize indexes when querying by MongoDB subdocument without known field names?


Yes, you can achieve this by indexing like “properties.k” for key and “properties.v” for value. The same is used to be implemented in ensureIndex().

Let us first see an example and create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

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

Output

This will produce the following output −

{
   "_id" : ObjectId("5e48de35dd099650a5401a42"),
   "details" : [
      {
         "StudentFirstName" : "Chris",
         "StudentLastName" : "Brown"
      },
      {
         "StudentFirstName" : "David",
         "StudentLastName" : "Miller"
      },
      {
         "StudentFirstName" : "John",
         "StudentLastName" : "Smith"
      },
      {
         "StudentFirstName" : "John",
         "StudentLastName" : "Doe"
      }
   ]
}

Following is the query to utilize indexes when querying by MongoDB subdocument without known field names −

> db.demo274.ensureIndex({"details.StudentFirstName": 1, "details.StudentLastName": 1});

Output

This will produce the following output −

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