Summary
Method Name | db.collection.find() |
Usage | Find documents in a collection or view |
Group | read |
Signature
db.collection.find(query, projection, options)
Usage
Find documents in a specific collection or a view. We can retrieve multiple documents from a collection(or view), based on some filters.
NOTES
- This command returns a cursor, we can iterate over the items using the cursor.
- Additionally we can use pretty() with the find, to format the output nicely, in the shell-
db.collection.find().pretty()
Arguments
Parameter | Description | Type | Optional |
---|---|---|---|
query | Filters for the document. Pass a document with the field and value. To get all the documents, don’t send this param or send an empty document. | document | True |
projection | Fields that we want to return in the result. Ignore this param, if you want to return all the fields. | document | True |
options | Additional options. | document | True |
NOTES
- To return all the documents use
db.collection.find({})
or justdb.collection.find()
. - We can use all the query operators like $and, $or, $eq, $gte, etc. in the query parameter.
Return Value
Return value | Case for the return value | Type |
---|---|---|
A cursor | On success this method returns a cursor to the documents that matches the provided option criteria. | cursor |
NOTES
- In Mongo Shell we get the result of the method directly. But as this command returnes a cursor, we can save the result of find method in MongoDB shell and then iterate over it-
var customers = db.customer.find();
while(customers.hasNext()) {
print(customer.next());
}
Examples
Here are a few examples of the method usage-
# MongoDB db.collection.find() method demo
# Insert some documents
bigboxcode> db.customer.insertMany([
{
"name": "Izabella Conroy",
"age": 19,
"phone": "108-679-2154",
"address": {
"street": "11 North Vineyard Drive",
"city": "Pueblo West",
"state": "CO",
"postalCode": "81007"
}
},
{
"name": "Alisa Parker",
"age": 72,
"phone": "768-319-1054",
"address": {
"street": "8532 Ingalls Circle",
"city": "Arvada",
"state": "CO",
"postalCode": "80003"
}
},
{
"name": "Eloise Weber",
"age": 29,
"phone": "618-357-2104",
"address": {
"street": "632 Belmar Drive",
"city": "Edmond",
"state": "OK",
"postalCode": "73025"
}
}
])
output>
{
acknowledged: true,
insertedIds: {
'0': ObjectId('65a8a2077de99c6d115fb6e5'),
'1': ObjectId('65a8a2077de99c6d115fb6e6'),
'2': ObjectId('65a8a2077de99c6d115fb6e7')
}
}
# Find all document from cutomer collection
bigboxcode> db.customer.find()
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e5'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
# Apply fitler where age=29
bigboxcode> db.customer.find({age: 29})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
# Apply filter where age >= 29
bigboxcode> db.customer.find({age: {$gte: 29}})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
# Use $or operator for the query filter
bigboxcode> db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e5'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
]
# Set projection to get name and phone only
bigboxcode> db.customer.find({}, { name: 1, phone: true})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e5'),
name: 'Izabella Conroy',
phone: '108-679-2154'
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
name: 'Alisa Parker',
phone: '768-319-1054'
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
name: 'Eloise Weber',
phone: '618-357-2104'
}
]
# Set projection to ignore name and phone field
bigboxcode> db.customer.find({}, { name: false, phone: 0})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e5'),
age: 19,
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
age: 72,
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
age: 29,
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
# Ignore nested property inside address
bigboxcode> db.customer.find({}, {"address.city": 0, age: 0, "address.street": false})
output>
[
{
_id: ObjectId('65a8a2077de99c6d115fb6e5'),
name: 'Izabella Conroy',
phone: '108-679-2154',
address: { state: 'CO', postalCode: '81007' }
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e6'),
name: 'Alisa Parker',
phone: '768-319-1054',
address: { state: 'CO', postalCode: '80003' }
},
{
_id: ObjectId('65a8a2077de99c6d115fb6e7'),
name: 'Eloise Weber',
phone: '618-357-2104',
address: { state: 'OK', postalCode: '73025' }
}
]
# Sort by age in assending order
bigboxcode> db.customer.find().sort({age: 1})
output>
{
_id: ObjectId("65b82c3618683e2d785ca6d1"),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
}
{
_id: ObjectId("65b82c3618683e2d785ca6d3"),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
{
_id: ObjectId("65b82c3618683e2d785ca6d2"),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
# Sort by age in descending order
bigboxcode> db.customer.find().sort({age: -1})
output>
{
_id: ObjectId("65b82c3618683e2d785ca6d2"),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
{
_id: ObjectId("65b82c3618683e2d785ca6d3"),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
{
_id: ObjectId("65b82c3618683e2d785ca6d1"),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
}
# Apply limit
bigboxcode> db.customer.find().sort({age: 1}).limit(2)
output>
{
_id: ObjectId("65b82c3618683e2d785ca6d1"),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
}
{
_id: ObjectId("65b82c3618683e2d785ca6d3"),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
# Skip certain results
bigboxcode> db.customer.find().sort({age: 1}).skip(2).limit(2)
output>
{
_id: ObjectId("65b82c3618683e2d785ca6d2"),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
NOTES
- Use dot(.) to access a field in a nested object, like –
address.street
Code Implementations
Here are the usage examples of the MongoDB method in NodeJS, Python, Golang, Java programming languages.
// MongoDB db.collection.find() method examples in Golang
package main
import (
"context"
"fmt"
"os"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"
func main() {
// Initiate mongo client
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
fmt.Println("MongoDB connection error: ", err)
os.Exit(1)
}
// Initiate collection instance
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
customerCollection := mongoClient.Database("bigboxcode").Collection("customer")
// Insert some documents
insertResult, err := customerCollection.InsertMany(ctx, []interface{}{
map[string]interface{}{
"name": "Izabella Conroy",
"age": 19,
"phone": "108-679-2154",
"address": map[string]interface{}{
"street": "11 North Vineyard Drive",
"city": "Pueblo West",
"state": "CO",
"postalCode": "81007",
},
},
map[string]interface{}{
"name": "Alisa Parker",
"age": 72,
"phone": "768-319-1054",
"address": map[string]interface{}{
"street": "8532 Ingalls Circle",
"city": "Arvada",
"state": "CO",
"postalCode": "80003",
},
},
map[string]interface{}{
"name": "Eloise Weber",
"age": 29,
"phone": "618-357-2104",
"address": map[string]interface{}{
"street": "632 Belmar Drive",
"city": "Edmond",
"state": "OK",
"postalCode": "73025",
},
},
})
if err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.insertMany() | Result: ", insertResult)
// Find all document from cutomer collection
cursor, err := customerCollection.Find(ctx, bson.M{})
if err != nil {
fmt.Println(err)
}
var findResult []bson.M
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find() | Result: ", findResult)
// Apply fitler where age=29
cursor, err = customerCollection.Find(ctx, bson.M{"age": 29})
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({"age": 29}) | Result: ", findResult)
// Apply filter where age >= 29
cursor, err = customerCollection.Find(ctx, bson.M{"age": bson.M{"$gte": 29}})
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({age: {$gte: 29}}) | Result: ", findResult)
// Use $or operator for the query filter
filter := bson.M{"$or": []bson.M{{"age": bson.M{"$gt": 29}}, {"address.postalCode": "81007"}}}
cursor, err = customerCollection.Find(ctx, filter)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result: ", findResult)
// Set projection to get name and phone only
findOptions := options.Find().SetProjection(bson.M{"name": 1, "phone": true})
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({}, { name: 1, phone: true}) | Result: ", findResult)
// Set projection to ignore name and phone field
findOptions = options.Find().SetProjection(bson.M{"name": false, "phone": 0})
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({}, { name: false, phone: 0}) | Result: ", findResult)
// Ignore nested property inside address
findOptions = options.Find().SetProjection(bson.M{"address.city": 0, "age": 0, "address.street": false})
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result: ", findResult)
// Sort by age in assending order
findOptions = options.Find().SetSort(bson.M{"age": 1})
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find().sort({age: 1}) | Result: ", findResult)
// Sort by age in descending order
findOptions = options.Find().SetSort(bson.M{"age": -1})
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find().sort({age: -1}) | Result: ", findResult)
// Apply limit
findOptions = options.Find().SetSort(bson.M{"age": 1}).SetLimit(2)
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find().sort({age: 1}).limit(2) | Result: ", findResult)
// Skip certain results
findOptions = options.Find().SetSort(bson.M{"age": 1}).SetLimit(2).SetSkip(2)
cursor, err = customerCollection.Find(ctx, bson.M{}, findOptions)
if err != nil {
fmt.Println(err)
}
if err := cursor.All(ctx, &findResult); err != nil {
fmt.Println(err)
}
fmt.Println("Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: ", findResult)
}
Output:
Command: db.customer.insertMany() | Result:
&{[ObjectID("65b846cb2b0b9702bc2fc086") ObjectID("65b846cb2b0b9702bc2fc087") ObjectID("65b846cb2b0b9702bc2fc088")]}
Command: db.customer.find() | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find({"age": 29}) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find({age: {$gte: 29}}) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054]]
Command: db.customer.find({}, { name: 1, phone: true}) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find({}, { name: false, phone: 0}) | Result: [map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[postalCode:81007 state:CO] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[postalCode:80003 state:CO] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[postalCode:73025 state:OK] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find().sort({age: 1}) | Result: [map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104] map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054]]
Command: db.customer.find().sort({age: -1}) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104] map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154]]
Command: db.customer.find().sort({age: 1}).limit(2) | Result:
[map[_id:ObjectID("65b846cb2b0b9702bc2fc086") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154] map[_id:ObjectID("65b846cb2b0b9702bc2fc088") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]]
Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: [map[_id:ObjectID("65b846cb2b0b9702bc2fc087") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054]]
NOTES
- Use the “
Find()
” method from “mongo-go-driver
“ - Signature of the method-
Find(ctx, filter, options)
// db.collection.find() method example in NodeJS
import { MongoClient } from "mongodb";
// Define MongoDB connection URI
const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";
// Create a client
const mongo = new MongoClient(uri);
await mongo.connect();
const database = mongo.db("bigboxcode");
const customerCollection = database.collection("customer");
// Insert some documents
let commandResult = await customerCollection.insertMany([
{
name: "Izabella Conroy",
age: 19,
phone: "108-679-2154",
address: {
street: "11 North Vineyard Drive",
city: "Pueblo West",
state: "CO",
postalCode: "81007",
},
},
{
name: "Alisa Parker",
age: 72,
phone: "768-319-1054",
address: {
street: "8532 Ingalls Circle",
city: "Arvada",
state: "CO",
postalCode: "80003",
},
},
{
name: "Eloise Weber",
age: 29,
phone: "618-357-2104",
address: {
street: "632 Belmar Drive",
city: "Edmond",
state: "OK",
postalCode: "73025",
},
},
]);
console.log("Command: db.customer.insertMany() | Result: ", commandResult);
// Find all document from cutomer collection
commandResult = await customerCollection.find().toArray();
console.log("Command: db.customer.find() | Result: ", commandResult);
// Apply fitler where age=29
commandResult = await customerCollection.find({ age: 29 }).toArray();
console.log("Command: db.customer.find() | Result: ", commandResult);
// Apply filter where age >= 29
commandResult = await customerCollection.find({ age: { $gte: 29 } }).toArray();
console.log(
"Command: db.customer.find({age: {$gte: 29}}) | Result: ",
commandResult
);
// Use $or operator for the query filter
commandResult = await customerCollection
.find({ $or: [{ age: { $gt: 29 } }, { "address.postalCode": "81007" }] })
.toArray();
console.log(
'Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result: ',
commandResult
);
// Set projection to get name and phone only
commandResult = await customerCollection
.find({}, { name: 1, phone: true })
.toArray();
console.log(
"Command: db.customer.find({}, { name: 1, phone: true}) | Result: ",
commandResult
);
// Set projection to ignore name and phone field
commandResult = await customerCollection
.find({}, { name: false, phone: 0 })
.toArray();
console.log(
"Command: db.customer.find({}, { name: false, phone: 0}) | Result: ",
commandResult
);
// Ignore nested property inside address
commandResult = await customerCollection
.find({}, { "address.city": 0, age: 0, "address.street": false })
.toArray();
console.log(
'Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result: ',
commandResult
);
// Sort by age in assending order
commandResult = await customerCollection.find().sort({age: 1}).toArray();
console.log(
'Command: db.customer.find().sort({age: 1}) | Result: ',
commandResult
);
// Sort by age in descending order
commandResult = await customerCollection.find().sort({age: -1}).toArray();
console.log(
'Command: db.customer.find().sort({age: -1}) | Result: ',
commandResult
);
// Apply limit
commandResult = await customerCollection.find().sort({age: 1}).limit(2).toArray();
console.log(
'Command: db.customer.find().sort({age: 1}).limit(2) | Result: ',
commandResult
);
// Skip certain results
commandResult = await customerCollection.find().sort({age: 1}).skip(2).limit(2).toArray();
console.log(
'Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: ',
commandResult
);
// Close connection
await mongo.close();
process.exit(0);
Output:
Command: db.customer.insertMany() | Result: {
acknowledged: true,
insertedCount: 3,
insertedIds: {
'0': new ObjectId('65b82fa52f36a58c20a835ab'),
'1': new ObjectId('65b82fa52f36a58c20a835ac'),
'2': new ObjectId('65b82fa52f36a58c20a835ad')
}
}
Command: db.customer.find() | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find() | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find({age: {$gte: 29}}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
]
Command: db.customer.find({}, { name: 1, phone: true}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find({}, { name: false, phone: 0}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find().sort({age: 1}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
]
Command: db.customer.find().sort({age: -1}) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
}
]
Command: db.customer.find().sort({age: 1}).limit(2) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ab'),
name: 'Izabella Conroy',
age: 19,
phone: '108-679-2154',
address: {
street: '11 North Vineyard Drive',
city: 'Pueblo West',
state: 'CO',
postalCode: '81007'
}
},
{
_id: new ObjectId('65b82fa52f36a58c20a835ad'),
name: 'Eloise Weber',
age: 29,
phone: '618-357-2104',
address: {
street: '632 Belmar Drive',
city: 'Edmond',
state: 'OK',
postalCode: '73025'
}
}
]
Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: [
{
_id: new ObjectId('65b82fa52f36a58c20a835ac'),
name: 'Alisa Parker',
age: 72,
phone: '768-319-1054',
address: {
street: '8532 Ingalls Circle',
city: 'Arvada',
state: 'CO',
postalCode: '80003'
}
}
]
NOTES
- Use NodeJS “
find()
” method from the package “mongodb“. - Method signatures are-
find(): FindCursor<WithId<TSchema>>
find(filter: Filter<TSchema>, options?: FindOptions): FindCursor<WithId<TSchema>>
find<T extends Document>(filter: Filter<TSchema>, options?: FindOptions): FindCursor<T>
- Definition of
FindOptions
–interface FindOptions<TSchema extends Document = Document> extends Omit<CommandOperationOptions, 'writeConcern'> {
limit?: number;
sort?: Sort;
projection?: Document;
skip?: number;
hint?: Hint;
timeout?: boolean;
tailable?: boolean;
awaitData?: boolean;
batchSize?: number;
returnKey?: boolean;
min?: Document;
max?: Document;
maxTimeMS?: number;
maxAwaitTimeMS?: number;
noCursorTimeout?: boolean;
collation?: CollationOptions;
allowDiskUse?: boolean;
singleBatch?: boolean;
allowPartialResults?: boolean;
showRecordId?: boolean;
let?: Document;
oplogReplay?: boolean;
} - Definition of
FindCursor
–class FindCursor<TSchema = any> extends AbstractCursor<TSchema> {
clone(): FindCursor<TSchema>;
map<T>(transform: (doc: TSchema) => T): FindCursor<T>;
count(options?: CountOptions): Promise<number>;
explain(verbosity?: ExplainVerbosityLike): Promise<Document>;
filter(filter: Document): this;
hint(hint: Hint): this;
min(min: Document): this;
max(max: Document): this;
returnKey(value: boolean): this;
showRecordId(value: boolean): this;
addQueryModifier(name: string, value: string | boolean | number | Document): this;
comment(value: string): this;
maxAwaitTimeMS(value: number): this;
maxTimeMS(value: number): this;
project<T extends Document = Document>(value: Document): FindCursor<T>;
sort(sort: Sort | string, direction?: SortDirection): this;
allowDiskUse(allow?: boolean): this;
collation(value: CollationOptions): this;
limit(value: number): this;
skip(value: number): this;
}
# db.collection.find() method example in Python
from pymongo import MongoClient
# Create MongoDB client
mongo_client = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")
# Select database and collection
mongo_database = mongo_client.bigboxcode
customer_collection = mongo_database.customer
# Insert some documents
command_result = customer_collection.insert_many([
{
"name": "Izabella Conroy",
"age": 19,
"phone": "108-679-2154",
"address": {
"street": "11 North Vineyard Drive",
"city": "Pueblo West",
"state": "CO",
"postalCode": "81007",
},
},
{
"name": "Alisa Parker",
"age": 72,
"phone": "768-319-1054",
"address": {
"street": "8532 Ingalls Circle",
"city": "Arvada",
"state": "CO",
"postalCode": "80003",
},
},
{
"name": "Eloise Weber",
"age": 29,
"phone": "618-357-2104",
"address": {
"street": "632 Belmar Drive",
"city": "Edmond",
"state": "OK",
"postalCode": "73025",
},
},
])
print("Command: db.customer.insertMany() | Result: ", command_result.inserted_ids)
# Find all documents from the customer collection
command_result = customer_collection.find()
print("Command: db.customer.find() | Result: ", list(command_result))
# Apply filter where age=29
command_result = customer_collection.find({"age": 29})
print("Command: db.customer.find({"age": 29}) | Result: ", list(command_result))
# Apply filter where age >= 29
command_result = customer_collection.find({"age": {"$gte": 29}})
print("Command: db.customer.find({age: {$gte: 29}}) | Result: ", list(command_result))
# Use $or operator for the query filter
command_result = customer_collection.find({"$or": [{"age": {"$gt": 29}}, {"address.postalCode": "81007"}]})
print('Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result: ', list(command_result))
# Set projection to get name and phone only
command_result = customer_collection.find({}, {"name": 1, "phone": True})
print("Command: db.customer.find({}, { name: 1, phone: true}) | Result: ", list(command_result))
# Set projection to ignore name and phone fields
command_result = customer_collection.find({}, {"name": False, "phone": 0})
print("Command: db.customer.find({}, { name: false, phone: 0}) | Result: ", list(command_result))
# Ignore nested property inside address
command_result = customer_collection.find({}, {"address.city": 0, "age": 0, "address.street": False})
print('Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result: ', list(command_result))
# Sort by age in ascending order
command_result = customer_collection.find().sort("age", 1)
print('Command: db.customer.find().sort({age: 1}) | Result: ', list(command_result))
# Sort by age in descending order
command_result = customer_collection.find().sort("age", -1)
print('Command: db.customer.find().sort({age: -1}) | Result: ', list(command_result))
# Apply limit
command_result = customer_collection.find().sort("age", 1).limit(2)
print('Command: db.customer.find().sort({age: 1}).limit(2) | Result: ', list(command_result))
# Skip certain results
command_result = customer_collection.find().sort("age", 1).skip(2).limit(2)
print('Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: ', list(command_result))
# Close connection
mongo_client.close()
Output:
Command: db.customer.insertMany() | Result:
[ObjectId('65b84db62cbad0a182ed0573'), ObjectId('65b84db62cbad0a182ed0574'), ObjectId('65b84db62cbad0a182ed0575')]
Command: db.customer.find() | Result: [{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find({"age": 29}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find({age: {$gte: 29}}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}]
Command: db.customer.find({}, { name: 1, phone: true}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'phone': '108-679-2154'}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'phone': '768-319-1054'}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'phone': '618-357-2104'}]
Command: db.customer.find({}, { name: false, phone: 0}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'age': 19, 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'age': 72, 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'age': 29, 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'phone': '108-679-2154', 'address': {'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'phone': '768-319-1054', 'address': {'state': 'CO', 'postalCode': '80003'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'phone': '618-357-2104', 'address': {'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find().sort({age: 1}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}, {'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}]
Command: db.customer.find().sort({age: -1}) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}, {'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}]
Command: db.customer.find().sort({age: 1}).limit(2) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0573'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}, {'_id': ObjectId('65b84db62cbad0a182ed0575'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}]
Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result:
[{'_id': ObjectId('65b84db62cbad0a182ed0574'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}]
NOTES
- Use method “
find
” from redis-py. - Signature of the method is –
def find(self, *args: Any, **kwargs: Any)
// db.collection.find() method example in Java
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import java.util.Arrays;
import java.util.List;
public class Find {
public static void main(String[] args) {
String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("bigboxcode");
MongoCollection<Document> customerCollection = database.getCollection("customer");
// Insert some documents
List<Document> documents = Arrays.asList(
new Document("name", "Izabella Conroy")
.append("age", 19)
.append("phone", "108-679-2154")
.append("address", new Document("street", "11 North Vineyard Drive")
.append("city", "Pueblo West")
.append("state", "CO")
.append("postalCode", "81007")),
new Document("name", "Alisa Parker")
.append("age", 72)
.append("phone", "768-319-1054")
.append("address", new Document("street", "8532 Ingalls Circle")
.append("city", "Arvada")
.append("state", "CO")
.append("postalCode", "80003")),
new Document("name", "Eloise Weber")
.append("age", 29)
.append("phone", "618-357-2104")
.append("address", new Document("street", "632 Belmar Drive")
.append("city", "Edmond")
.append("state", "OK")
.append("postalCode", "73025"))
);
customerCollection.insertMany(documents);
System.out.println("Command: db.customer.insertMany() | Result: " + documents);
// Find all documents from the customer collection
FindIterable<Document> findResults = customerCollection.find();
System.out.println("Command: db.customer.find() | Result: ");
MongoCursor<Document> findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Apply filter where age=29
findResults = customerCollection.find(Filters.eq("age", 29));
System.out.println("Command: db.customer.find() | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Apply filter where age >= 29
findResults = customerCollection.find(Filters.gte("age", 29));
System.out.println("Command: db.customer.find({age: {$gte: 29}}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Use $or operator for the query filter
findResults = customerCollection.find(Filters.or(Filters.gt("age", 29), Filters.eq("address.postalCode", "81007")));
System.out.println("Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Set projection to get name and phone only
findResults = customerCollection.find()
.projection(new Document("name", 1).append("phone", true));
System.out.println("Command: db.customer.find({}, { name: 1, phone: true}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Set projection to ignore name and phone fields
findResults = customerCollection.find()
.projection(new Document("name", false).append("phone", 0));
System.out.println("Command: db.customer.find({}, { name: false, phone: 0}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Ignore nested property inside address
findResults = customerCollection.find()
.projection(new Document("address.city", 0).append("age", 0).append("address.street", false));
System.out.println("Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Sort by age in ascending order
findResults = customerCollection.find().sort(Sorts.ascending("age"));
System.out.println("Command: db.customer.find().sort({age: 1}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Sort by age in descending order
findResults = customerCollection.find().sort(Sorts.descending("age"));
System.out.println("Command: db.customer.find().sort({age: -1}) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Apply limit
findResults = customerCollection.find().sort(Sorts.ascending("age")).limit(2);
System.out.println("Command: db.customer.find().sort({age: 1}).limit(2) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
// Skip certain results
findResults = customerCollection.find().sort(Sorts.ascending("age")).skip(2).limit(2);
System.out.println("Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result: ");
findResultCursor = findResults.iterator();
while (findResultCursor.hasNext()) {
System.out.println(findResultCursor.next());
}
}
}
}
Output:
Command: db.customer.insertMany() | Result:
[Document{{name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}, _id=65b8552c8d62d775440a0476}}, Document{{name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}, _id=65b8552c8d62d775440a0477}}, Document{{name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}, _id=65b8552c8d62d775440a0478}}]
Command: db.customer.find() | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Command: db.customer.find() | Result:
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Command: db.customer.find({age: {$gte: 29}}) | Result:
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Command: db.customer.find({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Command: db.customer.find({}, { name: 1, phone: true}) | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, phone=108-679-2154}}
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, phone=768-319-1054}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, phone=618-357-2104}}
Command: db.customer.find({}, { name: false, phone: 0}) | Result:
Document{{_id=65b8552c8d62d775440a0476, age=19, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0477, age=72, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Document{{_id=65b8552c8d62d775440a0478, age=29, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Command: db.customer.find({}, {"address.city": 0, age: 0, "address.street": false}) | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, phone=108-679-2154, address=Document{{state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, phone=768-319-1054, address=Document{{state=CO, postalCode=80003}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, phone=618-357-2104, address=Document{{state=OK, postalCode=73025}}}}
Command: db.customer.find().sort({age: 1}) | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Command: db.customer.find().sort({age: -1}) | Result:
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Command: db.customer.find().sort({age: 1}).limit(2) | Result:
Document{{_id=65b8552c8d62d775440a0476, name=Izabella Conroy, age=19, phone=108-679-2154, address=Document{{street=11 North Vineyard Drive, city=Pueblo West, state=CO, postalCode=81007}}}}
Document{{_id=65b8552c8d62d775440a0478, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}
Command: db.customer.find().sort({age: 1}).skip(2).limit(2) | Result:
Document{{_id=65b8552c8d62d775440a0477, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}
NOTES
- Use the method “
find()
” fromMongoCollection
. - Signatures of the method are-
FindIterable<TDocument> find()
FindIterable<TDocument> find(Bson filter)
FindIterable<TDocument> find(ClientSession clientSession)
FindIterable<TDocument> find(ClientSession clientSession, Bson filter)
Source Code
Use the following links to get the source code used in this article-
Source Code of | Source Code Link |
---|---|
Command Examples | GitHub |
NodeJS Implementation | GitHub |
Python Implementation | GitHub |
Golang Implementation | GitHub |
Java Implementation | GitHub |
Related Methods
Command | Details |
---|---|
db.collection.findOne() | Method Details |
db.collection.findAndModify() | Method Details |
db.collection.findOneAndUpdate() | Method Details |
db.collection.findOneAndReplace() | Method Details |
db.collection.findOneAndDelete() | Method Details |
db.collection.distinct() | Method Details |
db.collection.count() | Method Details |
db.collection.countDocuments() | Method Details |