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

MongoDBDatabaseBig Data Analytics

<p>Yes, you can achieve this by indexing like &ldquo;properties.k&rdquo; for key and &ldquo;properties.v&rdquo; 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 &minus;</p><pre class="prettyprint notranslate">&gt; db.demo274.insertOne({&quot;details&quot;:[{StudentFirstName:&quot;Chris&quot;,StudentLastName:&quot;Brown&quot;}, ... &nbsp; {StudentFirstName:&quot;David&quot;,StudentLastName:&quot;Miller&quot;}, ... &nbsp; {StudentFirstName:&quot;John&quot;,StudentLastName:&quot;Smith&quot;}, ... &nbsp; {StudentFirstName:&quot;John&quot;,StudentLastName:&quot;Doe&quot;} ...] ...} ...); { &nbsp; &nbsp;&quot;acknowledged&quot; : true, &nbsp; &nbsp;&quot;insertedId&quot; : ObjectId(&quot;5e48de35dd099650a5401a42&quot;) }</pre><p>Display all documents from a collection with the help of find() method &minus;</p><pre class="prettyprint notranslate">&gt; db.demo274.find().pretty();</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5e48de35dd099650a5401a42&quot;), &nbsp; &nbsp;&quot;details&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentFirstName&quot; : &quot;Chris&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentLastName&quot; : &quot;Brown&quot; &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentFirstName&quot; : &quot;David&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentLastName&quot; : &quot;Miller&quot; &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentFirstName&quot; : &quot;John&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentLastName&quot; : &quot;Smith&quot; &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentFirstName&quot; : &quot;John&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;StudentLastName&quot; : &quot;Doe&quot; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] }</pre><p>Following is the query to utilize indexes when querying by MongoDB subdocument without known field names &minus;</p><pre class="prettyprint notranslate">&gt; db.demo274.ensureIndex({&quot;details.StudentFirstName&quot;: 1, &quot;details.StudentLastName&quot;: 1});</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &nbsp; &nbsp;&quot;createdCollectionAutomatically&quot; : false, &nbsp; &nbsp;&quot;numIndexesBefore&quot; : 1, &nbsp; &nbsp;&quot;numIndexesAfter&quot; : 2, &nbsp; &nbsp;&quot;ok&quot; : 1 }</pre>
raja
Updated on 31-Mar-2020 13:10:51

Advertisements