How to find if element exists in document - MongoDB?

MongoDBDatabaseBig Data Analytics

To find if element exists in a MongoDB document, use MongoDB $exists. Let us create a collection with documents −

> db.demo497.insertOne({"details":[{"Name":"Chris"},{"Name":"Bob"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3cfb0f3fa88e22790d1")
}
> db.demo497.insertOne({"details":[{"Name":"Carol"}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3d9b0f3fa88e22790d2")
}
> db.demo497.insertOne({"details":[{}]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84b3e9b0f3fa88e22790d3")
}

Display all documents from a collection with the help of find() method −

> db.demo497.find();

This will produce the following output −

{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3d9b0f3fa88e22790d2"), "details" : [ { "Name" : "Carol" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }

Following is the query to find if element exists in a document −

> db.demo497.find({$or:[
...       {"details.Name" : {$ne : "Carol"}},
...       {details: {$exists: false}}
...    ]
... });

This will produce the following output −

{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }
raja
Published on 13-May-2020 09:10:32
Advertisements