How do I query a MongoDB collection?

MongoDBDatabaseBig Data Analytics

To query or return a MongoDB collection, use getCollection(). Let us create a collection with documents −

> db.demo294.insertOne({"EmployeeId":101,"EmployeeName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a1a5d93261e4bc9ea36")
}
> db.demo294.insertOne({"EmployeeId":102,"EmployeeName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a255d93261e4bc9ea37")
}
> db.demo294.insertOne({"EmployeeId":103,"EmployeeName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d4a335d93261e4bc9ea38")
}

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

> db.demo294.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e4d4a255d93261e4bc9ea37"), "EmployeeId" : 102, "EmployeeName" : "Bob" }
{ "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }

Following is the query to get MongoDB collection −

> db.getCollection('demo294').find({
...   "EmployeeId":{$in:[101,103]}});

This will produce the following output −

{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
raja
Published on 01-Apr-2020 10:41:55
Advertisements