

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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?
<p>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().</p><p>Let us first see an example and create a collection with documents −</p><pre class="prettyprint notranslate">> 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") }</pre><p>Display all documents from a collection with the help of find() method −</p><pre class="prettyprint notranslate">> db.demo274.find().pretty();</pre><h2>Output</h2><p>This will produce the following output −</p><pre class="result notranslate">{ "_id" : ObjectId("5e48de35dd099650a5401a42"), "details" : [ { "StudentFirstName" : "Chris", "StudentLastName" : "Brown" }, { "StudentFirstName" : "David", "StudentLastName" : "Miller" }, { "StudentFirstName" : "John", "StudentLastName" : "Smith" }, { "StudentFirstName" : "John", "StudentLastName" : "Doe" } ] }</pre><p>Following is the query to utilize indexes when querying by MongoDB subdocument without known field names −</p><pre class="prettyprint notranslate">> db.demo274.ensureIndex({"details.StudentFirstName": 1, "details.StudentLastName": 1});</pre><h2>Output</h2><p>This will produce the following output −</p><pre class="result notranslate">{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }</pre>
- Related Questions & Answers
- Sort by subdocument in MongoDB
- How to improve querying field in MongoDB?
- MongoDB to sort by subdocument match?
- MongoDB indexes not working when executing $elemMatch?
- How can I aggregate collection and group by field count in MongoDB?
- Querying object's field array values in MongoDB?
- How can I change the field name in MongoDB?
- MySQL pagination without double-querying?
- Querying with MongoDB subelement?
- MongoDB query by sub-field?
- Which characters are NOT allowed in MongoDB field names?
- Querying only the field name and display only the id in MongoDB?
- How can I rename a field for all documents in MongoDB?
- Can I retrieve multiple documents from MongoDB by id?
- Rebuilding indexes in MongoDB?
Advertisements