
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements