MongoDB: Find Documents in Collection using find() function for expert

0 0
Read Time:4 Minute, 20 Second

MongoDB provides two methods for finding/retrieve documents from a collection:

  1. findOne() Рreturns a the first document that matched with the specified criteria.
  2. find() Рreturns a cursor to the selected documents that matched with the specified criteria.

The following inserts documents in the employees collection.

db.employees.insertMany([
    { 
        _id:1,
        firstName: "John",
        lastName: "King",
        email: "john.king@abc.com",
        salary: 5000,
        skills: [ "Angular", "React", "MongoDB" ],
        department: { 
                    "name":"IT" 
                }
    },
    { 
        _id:2,
        firstName: "Sachin",
        lastName: "T",
        email: "sachin.t@abc.com",
        salary: 8000,
        skills: [ "Accounting", "Tax" ],
        department: { 
                    "name":"Finance" 
                }
    },
    { 
        _id:3,
        firstName: "James",
        lastName: "Bond",
        email: "jamesb@abc.com",
        salary: 7500,
        skills: [ "Sales", "Marketing" ],
        department: { 
                    "name":"Marketing" 
                }
    },
    { 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "steve.j@abc.com",
        salary: 7000

    },
    { 
        _id:5,
        firstName: "Kapil",
        lastName: "D",
        email: "kapil.d@abc.com",
        salary: 4500,
        skills: [ "Accounting", "Tax" ],
        department: { 
                    "name":"Finance" 
                }

    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "amitabh.b@abc.com",
        salary: 7000
    }
])

Find Documents using the find() Method

The find() method finds all the documents that matches with the specified criteria and returns the cursor object. The cursor object is a pointer to the result set.

Syntax:

db.collection.find(query, projection)

Parameters:

  1. query: Optional. Specifies the criteria using query operators.
  2. projection: Optional. Specifies the fields to include in a resulted document.

The find() returns all the documents from a collection if no parameter is passed. The following executes the db.employees.find() in mongosh shell:

humanResourceDB> db.employees.find()
[
    { 
        _id:1,
        firstName: "John",
        lastName: "King",
        email: "john.king@abc.com",
        salary: 5000,
        skills: [ "Angular", "React", "MongoDB" ],
        department: { "name":"IT" }
    },
    { 
        _id:2,
        firstName: "Sachin",
        lastName: "T",
        email: "sachin.t@abc.com",
        salary: 8000,
        skills: [ "Accounting", "Tax" ],
        department: { "name":"Finance" }
    },
    { 
        _id:3,
        firstName: "James",
        lastName: "Bond",
        email: "jamesb@abc.com",
        salary: 7500,
        skills: [ "Sales", "Marketing" ],
        department: { "name":"Marketing" }
    },
    { 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "steve.j@abc.com",
        salary: 7000

    },
    { 
        _id:5,
        firstName: "Kapil",
        lastName: "D",
        email: "kapil.d@abc.com",
        salary: 4500,
        skills: [ "Accounting", "Tax" ],
        department: { "name":"Finance" }

    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "amitabh.b@abc.com",
        salary: 7000
    }
]

Executing db.collection.find() in mongosh shell automatically iterates the cursor to display up to the first 20 documents. Type it to continue iteration.

You can specify the criteria as { field: "value", field:"value",..} on which you want to find a document. For example, the following returns all the documents where salary is 7000.

Example: find(criteria) 

db.employees.find({salary: 7000})

Output

[{ 
        _id:4,
        firstName: "Steve",
        lastName: "J",
        email: "steve.j@abc.com",
        salary: 7000

    },
    { 
        _id:6,
        firstName: "Amitabh",
        lastName: "B",
        email: "amitabh.b@abc.com",
        salary: 7000
    }
]

The find() method performs the case-sensitive search, so {firstName: "Kapil"} and {firstName: "kapil"} returns different result.

Use the query operators for more refined search. For example, the following finds the first document where salary is greater than 8000.

Example: find() with Query Operator Copy

db.employees.find({salary: {$gt: 7000}})

Output:

[{
    _id: 2,
    firstName: 'Gaurav',
    lastName: 'Dixit',
    email: 'gaurav.dixit@codedixa.com',
    salary: 8000,
    skills: [ 'Accounting', 'Tax' ],
    department: { name: 'Finance' }
  },
  {
    _id: 3,
    firstName: 'James',
    lastName: 'Bond',
    email: 'jamesb@abc.com',
    salary: 7500,
    skills: [ 'Sales', 'Marketing' ],
    department: { name: 'Marketing' }
  }]

Specify multiple criteria by adding another query operator as field. The following retrieves documents whose salary field is greater than 7000 and less than 8000.

Example: find() with Multiple Query Operator

db.employees.find({salary: {$gt: 7000, $lt: 8000}})

Output:

[{
    _id: 3,
    firstName: 'James',
    lastName: 'Bond',
    email: 'jamesb@abc.com',
    salary: 7500,
    skills: [ 'Sales', 'Marketing' ],
    department: { name: 'Marketing' }
  }]

Query Embedded Document

You can specify criteria for embedded document fields using dot notation, as shown below.

Example: find() with Multiple Query Operator 

db.employees.find({ "department.name": "Finance"})

Output:

[
  {
    _id: 2,
    firstName: 'Sachin',
    lastName: 'T',
    email: 'sachin.t@abc.com',
    salary: 8000,
    skills: [ 'Accounting', 'Tax' ],
    department: { name: 'Finance' }
  },
  {
    _id: 5,
    firstName: 'Kapil',
    lastName: 'D',
    email: 'kapil.d@abc.com',
    salary: 4500,
    skills: [ 'Accounting', 'Tax' ],
    department: { name: 'Finance' }
  }
]

Query Array Elements

You can find documents based on the array element, index, or size.

Example: find() on Array

db.employees.find({ "skills": "Tax"}) //returns documents where skills contains "Tax"
db.employees.find({ "skills":  { $in: [ "Tax", "Sales" ]}}) //returns documents where skills contains "Tax" or "Sales"
db.employees.find({ "skills":  { $all: [ "Tax", "Accounting" ]}}) //returns documents where skills contains "Tax" and "Accounting"
db.employees.find({ "skills":  { $size: 3}) //returns documents where skills contains 3 elements

Projection

Use the projection parameter to specify the fields to be included in the result. The projection parameter format is {<field>: <1 or true>, <field>: <1 or true>...} where 1 or true includes the field, and o or false excludes the field in the result.

Example: find()

db.employees.find({salary: 7000}, {firstName:1, lastName:1})

Output:

[{ 
    _id:4,
    firstName: "Steve",
    lastName: "J",
},
{ 
    _id:6,
    firstName: "Amitabh",
    lastName: "B",
}]

Note that by default, the _id field will be included in the result. To omit it, specify { _id:0 } in the projection.

Example: find() 

db.employees.findOne({firstName: "Sachin"}, {_id: 0, firstName:1, lastName:1})

Output:

[{ 
    firstName: "Steve",
    lastName: "J",
},
{ 
    firstName: "Amitabh",
    lastName: "B",
}]
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

4 thoughts on “MongoDB: Find Documents in Collection using find() function for expert

Leave a Comment