How to determine whether a field exists in MongoDB?

MongoDBDatabaseBig Data Analytics

<p>You need to use $exists operator to determine whether a field exists in MongoDB. Let us first create a collection with documents</p><pre class="prettyprint notranslate">&gt; db.determineFieldExistsDemo.insertOne({&quot;ClientName&quot;:&quot;John&quot;}); { &nbsp; &nbsp;&quot;acknowledged&quot; : true, &nbsp; &nbsp;&quot;insertedId&quot; : ObjectId(&quot;5c9eb245d628fa4220163b75&quot;) } &gt; db.determineFieldExistsDemo.insertOne({&quot;ClientName&quot;:&quot;Larry&quot;,&quot;ClientAge&quot;:23}); { &nbsp; &nbsp;&quot;acknowledged&quot; : true, &nbsp; &nbsp;&quot;insertedId&quot; : ObjectId(&quot;5c9eb25cd628fa4220163b76&quot;) } &gt; db.determineFieldExistsDemo.insertOne({&quot;ClientName&quot;:&quot;Mike&quot;,&quot;ClientCountryName&quot;:&quot;UK&quot;}); { &nbsp; &nbsp;&quot;acknowledged&quot; : true, &nbsp; &nbsp;&quot;insertedId&quot; : ObjectId(&quot;5c9eb26fd628fa4220163b77&quot;) } &gt; db.determineFieldExistsDemo.insertOne({&quot;ClientName&quot;:&quot;Sam&quot;,&quot;ClientAge&quot;:24}); { &nbsp; &nbsp;&quot;acknowledged&quot; : true, &nbsp; &nbsp;&quot;insertedId&quot; : ObjectId(&quot;5c9eb286d628fa4220163b78&quot;) }</pre><p>Following is the query to display all documents from a collection with the help of find() method</p><pre class="prettyprint notranslate">&gt; db.determineFieldExistsDemo.find().pretty();</pre><p>This will produce the following output</p><pre class="result notranslate">{ &quot;_id&quot; : ObjectId(&quot;5c9eb245d628fa4220163b75&quot;), &quot;ClientName&quot; : &quot;John&quot; } { &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5c9eb25cd628fa4220163b76&quot;), &nbsp; &nbsp;&quot;ClientName&quot; : &quot;Larry&quot;, &nbsp; &nbsp;&quot;ClientAge&quot; : 23 } { &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5c9eb26fd628fa4220163b77&quot;), &nbsp; &nbsp;&quot;ClientName&quot; : &quot;Mike&quot;, &nbsp; &nbsp;&quot;ClientCountryName&quot; : &quot;UK&quot; } { &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5c9eb286d628fa4220163b78&quot;), &nbsp; &nbsp;&quot;ClientName&quot; : &quot;Sam&quot;, &nbsp; &nbsp;&quot;ClientAge&quot; : 24 }</pre><p>Following is the query to determine whether a field exists</p><pre class="prettyprint notranslate">&gt; db.determineFieldExistsDemo.find({ClientCountryName:{$exists:true}}).pretty();</pre><p>This will produce the following output</p><pre class="result notranslate">{ &nbsp; &nbsp;&quot;_id&quot; : ObjectId(&quot;5c9eb26fd628fa4220163b77&quot;), &nbsp; &nbsp;&quot;ClientName&quot; : &quot;Mike&quot;, &nbsp; &nbsp;&quot;ClientCountryName&quot; : &quot;UK&quot; }</pre>
raja
Updated on 30-Jul-2019 22:30:25

Advertisements