How to select MongoDB document that does not consist a specific field?

MongoDBDatabaseBig Data Analytics

<p>Check for a specific field using MongoDB <span>$</span>exists. If that field does not exist in a document, then you need to display the same document with find().</p><p>Let us create a collection with documents &minus;</p><pre class="prettyprint notranslate">&gt; db.demo612.insertOne({id:1,&quot;Info&quot;:[{Name:&quot;Chris&quot;,Age:21},{Name:&quot;David&quot;}]});{ &nbsp; &nbsp;&quot;acknowledged&quot; : true, &quot;insertedId&quot; : ObjectId(&quot;5e987372f6b89257f5584d87&quot;) }</pre><p>Display all documents from a collection with the help of find() method &minus;</p><pre class="prettyprint notranslate">&gt; db.demo612.find().pretty();</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5e987372f6b89257f5584d87&quot;), &nbsp; &nbsp;&quot;id&quot; : 1, &nbsp; &nbsp;&quot;Info&quot; : [ &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : &quot;Chris&quot;, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Age&quot; : 21 &nbsp; &nbsp; &nbsp; }, &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;Name&quot; : &quot;David&quot; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;] }</pre><p>Following is the query to fetch a MongoDB document that does not consist of a specific field &minus;</p><pre class="result notranslate">&gt; db.demo612.aggregate({$unwind: &quot;$Info&quot;}, ... {$match: {&quot;Info.Age&quot;:{$exists: false}}}, ... {$project: {&quot;Info.Name&quot;: 1}})</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">{ &quot;_id&quot; : ObjectId(&quot;5e987372f6b89257f5584d87&quot;), &quot;Info&quot; : { &quot;Name&quot; : &quot;David&quot; } }</pre>
raja
Updated on 15-May-2020 08:09:00

Advertisements