Filter documents in MongoDB using simple query?

MongoDBDatabaseBig Data Analytics

You can use $match. The $match filters the documents to pass only the documents that match the specified condition to the next pipeline stage. Let us create a collection with documents −

> db.demo629.insertOne(
...    {
...
...       "Subject": [
...          "MySQL",
...          "MongoDB"
...       ],
...       "details": [
...          {
...             Name:"Chris",
...             "Marks":78
...          },
...          { Name:"David",
...             "Marks":89
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ae9f56c954c74be91e6b9")
}

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

> db.demo629.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ae9f56c954c74be91e6b9"), "Subject" : [ "MySQL", "MongoDB" ], "details" : [ { "Name" : "Chris", "Marks" : 78 }, { "Name" : "David", "Marks" : 89 } ] }

Following is the query to filter documents in MongoDB using simple query −

> db.demo629.aggregate([
...    {"$unwind": "$details"},
...    {"$match": {"details.Name": 'Chris', "Subject": {"$in":["Java","MySQL","Python","C","C++"]}}},
...    {"$project": {"details": 1, "_id": 0}}
... ]);

This will produce the following output −

{ "details" : { "Name" : "Chris", "Marks" : 78 } }
raja
Published on 12-May-2020 10:44:57
Advertisements