MongoDB Method: db.collection.findOne()

Summary

Method Namedb.collection.findOne()
UsageFind first document in a collection or view
Group read

Signature

db.collection.findOne(query, projection, options)

Usage

Find the first document in a specific collection or view, that matches the provided filter. We get a single document that fulfills the criteria.

NOTES

  • If the provided criteria match multiple documents in the collection/view, then this command returns the first document.
  • If no sorting condition is provided, then MongoDB uses the natural order. And the natural order is the order in which sequence the data is stored in the storage space.
  • In fixed-size collections(Capped collection) natural order is the order in which data was inserted.

Arguments

ParameterDescriptionTypeOptional
queryFilters 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.
documentTrue
projectionFields that we want to return in the result.
Ignore this param, if you want to return all the fields.
documentTrue
optionsAdditional options.documentTrue

NOTES

  • To ignore providing any filter use db.collection.findOne({}) or just db.collection.findOne().
  • We can use all the query operators like $and, $or, $eq, $gte, etc. in the query parameter.
  • We can decide which field to return or ignore in the result. the _id field is included until it is explicitly ignored in the projection.

Return Value

Return valueCase for the return valueType
A documentOn success this method returns a documentdocument

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.findOne() 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('65be325487bc09975c93a972'),
    '1': ObjectId('65be325487bc09975c93a973'),
    '2': ObjectId('65be325487bc09975c93a974')
  }
}


# Find one document from cutomer collection
bigboxcode>  db.customer.findOne()

output:
{
  _id: ObjectId('65be325487bc09975c93a972'),
  name: 'Izabella Conroy',
  age: 19,
  phone: '108-679-2154',
  address: {
    street: '11 North Vineyard Drive',
    city: 'Pueblo West',
    state: 'CO',
    postalCode: '81007'
  }
}


# Apply fitler where age=29
bigboxcode> db.customer.findOne({age: 29})

output:
{
  _id: ObjectId('65be325487bc09975c93a974'),
  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.findOne({age: {$gte: 29}})

output:
{
  _id: ObjectId('65be325487bc09975c93a973'),
  name: 'Alisa Parker',
  age: 72,
  phone: '768-319-1054',
  address: {
    street: '8532 Ingalls Circle',
    city: 'Arvada',
    state: 'CO',
    postalCode: '80003'
  }
}


# Use $or operator for the query filter
bigboxcode> db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]})

output:
{
  _id: ObjectId('65be325487bc09975c93a972'),
  name: 'Izabella Conroy',
  age: 19,
  phone: '108-679-2154',
  address: {
    street: '11 North Vineyard Drive',
    city: 'Pueblo West',
    state: 'CO',
    postalCode: '81007'
  }
}


# Set projection to get name, phone, and postalCode only
bigboxcode>  db.customer.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1})

output:
{
  _id: ObjectId('65be325487bc09975c93a974'),
  name: 'Eloise Weber',
  phone: '618-357-2104',
  address: { postalCode: '73025' }
}


# Ignore properties
bigboxcode> db.customer.findOne({}, { name: false, phone: 0, "address.city": 0})

output:
{
  _id: ObjectId('65be325487bc09975c93a972'),
  age: 19,
  address: {
    street: '11 North Vineyard Drive',
    state: 'CO',
    postalCode: '81007'
  }
}


# Apply filter that doesn't return any result
bigboxcode> db.customer.findOne({age: 299999999})

output:
null


# Use regex to filter by matching value of a field
bigboxcode> db.customer.findOne({name: {$regex : /^alisa/i}})

output:
{
  _id: ObjectId('65be325487bc09975c93a973'),
  name: 'Alisa Parker',
  age: 72,
  phone: '768-319-1054',
  address: {
    street: '8532 Ingalls Circle',
    city: 'Arvada',
    state: 'CO',
    postalCode: '80003'
  }
}

# Use regex
bigboxcode> db.customer.findOne({"address.street": {$regex : /drive/i}})

output:
{
  _id: ObjectId('65be325487bc09975c93a972'),
  name: 'Izabella Conroy',
  age: 19,
  phone: '108-679-2154',
  address: {
    street: '11 North Vineyard Drive',
    city: 'Pueblo West',
    state: 'CO',
    postalCode: '81007'
  }
}


# Try to use findOne() one a non existing collection
# We get null
bigboxcode> db.wrong_collection.findOne()

output:
null

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.

// db.collection.findOne() 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");
const wrongCollection = database.collection("wrong_collection");

// 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 one document from cutomer collection
commandResult = await customerCollection.findOne();

console.log("Command: db.customer.findOne() | Result: ", commandResult);

// Apply fitler where age=29
commandResult = await customerCollection.findOne({ age: 29 });

console.log(
  "Command: db.customer.findOne({age: 29}) | Result: ",
  commandResult
);

// Apply filter where age >= 29
commandResult = await customerCollection.findOne({ age: { $gte: 29 } });

console.log(
  "Command: db.customer.findOne({age: {$gte: 29}}) | Result: ",
  commandResult
);

// Use $or operator for the query filter
commandResult = await customerCollection.findOne({
  $or: [{ age: { $gt: 29 } }, { "address.postalCode": "81007" }],
});

console.log(
  'Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result: ',
  commandResult
);

// Set projection to get name, phone, and postalCode only
commandResult = await customerCollection.findOne(
  { age: 29 },
  { name: 1, phone: true, "address.postalCode": 1 }
);

console.log(
  'Command: db.customer.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result: ',
  commandResult
);

// Ignore properties
commandResult = await customerCollection.findOne(
  {},
  { name: false, phone: 0, "address.city": 0 }
);

console.log(
  'Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result: ',
  commandResult
);

// Apply filter that doesn't return any result
commandResult = await customerCollection.findOne({ age: 299999999 });

console.log(
  "Command: db.customer.findOne({age: 299999999}) | Result: ",
  commandResult
);

// Use regex to filter by matching value of a field
commandResult = await customerCollection.findOne({
  name: { $regex: /^alisa/i },
});

console.log(
  "Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result: ",
  commandResult
);

// Use regex
commandResult = await customerCollection.findOne({
  "address.street": { $regex: /drive/i },
});

console.log(
  'Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result: ',
  commandResult
);

// Try to use findOne() one a non existing collection, We get null
commandResult = await wrongCollection.findOne();

console.log("Command: db.wrong_collection.findOne() | Result: ", commandResult);

// Close connection
await mongo.close();

process.exit(0);

Output:

Command: db.customer.insertMany() | Result:  {
  acknowledged: true,
  insertedCount: 3,
  insertedIds: {
    '0': new ObjectId('65bfa13b33c6e85418509e6d'),
    '1': new ObjectId('65bfa13b33c6e85418509e6e'),
    '2': new ObjectId('65bfa13b33c6e85418509e6f')
  }
}

Command: db.customer.findOne() | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6d'),
  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.findOne({age: 29}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6f'),
  name: 'Eloise Weber',
  age: 29,
  phone: '618-357-2104',
  address: {
    street: '632 Belmar Drive',
    city: 'Edmond',
    state: 'OK',
    postalCode: '73025'
  }
}

Command: db.customer.findOne({age: {$gte: 29}}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6e'),
  name: 'Alisa Parker',
  age: 72,
  phone: '768-319-1054',
  address: {
    street: '8532 Ingalls Circle',
    city: 'Arvada',
    state: 'CO',
    postalCode: '80003'
  }
}

Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6d'),
  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.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6f'),
  name: 'Eloise Weber',
  age: 29,
  phone: '618-357-2104',
  address: {
    street: '632 Belmar Drive',
    city: 'Edmond',
    state: 'OK',
    postalCode: '73025'
  }
}

Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6d'),
  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.findOne({age: 299999999}) | Result:  null
Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6e'),
  name: 'Alisa Parker',
  age: 72,
  phone: '768-319-1054',
  address: {
    street: '8532 Ingalls Circle',
    city: 'Arvada',
    state: 'CO',
    postalCode: '80003'
  }
}

Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result:  {
  _id: new ObjectId('65bfa13b33c6e85418509e6d'),
  name: 'Izabella Conroy',
  age: 19,
  phone: '108-679-2154',
  address: {
    street: '11 North Vineyard Drive',
    city: 'Pueblo West',
    state: 'CO',
    postalCode: '81007'
  }
}

Command: db.wrong_collection.findOne() | Result:  null

NOTES

  • Use NodeJS “findOne()” method from the package “mongodb“.
  • Method signatures are-
    • findOne(): Promise<WithId<TSchema> | null>
    • findOne(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>
    • findOne(filter: Filter<TSchema>, options: FindOptions): Promise<WithId<TSchema> | null>
    • findOne<T = TSchema>(): Promise<T | null>
    • findOne<T = TSchema>(filter: Filter<TSchema>): Promise<T | null>
    • findOne<T = TSchema>(filter: Filter<TSchema>, options?: FindOptions): Promise<T | null>
  • 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;
    }
# db.collection.findOne() method example in Python

from pymongo import MongoClient
import re

# 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
wrong_collection = mongo_database.wrong_collection


# 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 one document from cutomer collection
commandResult = customer_collection.find_one()

print("Command: db.customer.findOne() | Result: ", commandResult)

# Apply fitler where age=29
commandResult = customer_collection.find_one({"age": 29})

print("Command: db.customer.findOne({age: 29}) | Result: ", commandResult)

# Apply filter where age >= 29
commandResult = customer_collection.find_one({"age": {"$gte": 29}})

print("Command: db.customer.findOne({age: {$gte: 29}}) | Result: ", commandResult)

# Use $or operator for the query filter
commandResult = customer_collection.find_one(
    {
        "$or": [{"age": {"$gt": 29}}, {"address.postalCode": "81007"}],
    }
)

print(
    'Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result: ',
    commandResult,
)

# Set projection to get name, phone, and postalCode only
commandResult = customer_collection.find_one(
    {"age": 29}, {"name": 1, "phone": True, "address.postalCode": 1}
)

print(
    'Command: db.customer.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result: ',
    commandResult,
)

# Ignore properties
commandResult = customer_collection.find_one(
    {}, {"name": False, "phone": 0, "address.city": 0}
)

print(
    'Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result: ',
    commandResult,
)

# Apply filter that doesn't return any result
commandResult = customer_collection.find_one({"age": 299999999})

print("Command: db.customer.findOne({age: 299999999}) | Result: ", commandResult)

# Use regex to filter by matching value of a field
regex_pattern = re.compile("^alisa", re.IGNORECASE)
commandResult = customer_collection.find_one(
    {
        "name": {"$regex": regex_pattern},
    }
)

print(
    "Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result: ",
    commandResult,
)

# Use regex
regex_pattern = re.compile("drive", re.IGNORECASE)
commandResult = customer_collection.find_one(
    {
        "address.street": {"$regex": regex_pattern},
    }
)

print(
    'Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result: ',
    commandResult,
)

# Try to use findOne() one a non existing collection, We get null
commandResult = wrong_collection.find_one()

print("Command: db.wrong_collection.findOne() | Result: ", commandResult)


# Close connection
mongo_client.close()

Output:

Command: db.customer.insertMany() | Result:  [ObjectId('65bfbece680b9d78037609d4'), ObjectId('65bfbece680b9d78037609d5'), ObjectId('65bfbece680b9d78037609d6')]

Command: db.customer.findOne() | Result:  {'_id': ObjectId('65bfbece680b9d78037609d4'), '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.findOne({age: 29}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d6'), 'name': 'Eloise Weber', 'age': 29, 'phone': '618-357-2104', 'address': {'street': '632 Belmar Drive', 'city': 'Edmond', 'state': 'OK', 'postalCode': '73025'}}

Command: db.customer.findOne({age: {$gte: 29}}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d5'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}

Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d4'), '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.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d6'), 'name': 'Eloise Weber', 'phone': '618-357-2104', 'address': {'postalCode': '73025'}}

Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d4'), 'age': 19, 'address': {'street': '11 North Vineyard Drive', 'state': 'CO', 'postalCode': '81007'}}

Command: db.customer.findOne({age: 299999999}) | Result:  None

Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d5'), 'name': 'Alisa Parker', 'age': 72, 'phone': '768-319-1054', 'address': {'street': '8532 Ingalls Circle', 'city': 'Arvada', 'state': 'CO', 'postalCode': '80003'}}

Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result:  {'_id': ObjectId('65bfbece680b9d78037609d4'), 'name': 'Izabella Conroy', 'age': 19, 'phone': '108-679-2154', 'address': {'street': '11 North Vineyard Drive', 'city': 'Pueblo West', 'state': 'CO', 'postalCode': '81007'}}

Command: db.wrong_collection.findOne() | Result:  None

NOTES

  • Use method “find_one” from redis-py.
  • Signature of the method is –
    • def find_one(self, filter: Optional[Any] = None, *args: Any, **kwargs: Any)
// MongoDB db.collection.findOne() method examples in Golang

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"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)
	}
	defer mongoClient.Disconnect(context.Background())

	// Initiate collection instance
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	customerCollection := mongoClient.Database("bigboxcode").Collection("customer")
	wrongCollection := mongoClient.Database("bigboxcode").Collection("wrong_collection")

	// 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)

	var commandResult bson.M

	// Find one document from cutomer collection
	err = customerCollection.FindOne(ctx, bson.M{}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne() | Result: ", commandResult)

	// Apply fitler where age=29
	err = customerCollection.FindOne(ctx, bson.M{"age": 29}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({age: 29}) | Result: ", commandResult)

	// Apply filter where age >= 29
	err = customerCollection.FindOne(ctx, bson.M{"age": bson.M{"$gte": 29}}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({age: {$gte: 29}}) | Result: ", commandResult)

	// Use $or operator for the query filter
	filter := bson.M{"$or": []bson.M{{"age": bson.M{"$gt": 29}}, {"address.postalCode": "81007"}}}
	err = customerCollection.FindOne(ctx, filter).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {\"address.postalCode\": \"81007\"}]}) | Result: ", commandResult)

	// Set projection to get name, phone, and postalCode only
	findOptions := options.FindOne().SetProjection(bson.M{"name": 1, "phone": true, "address.postalCode": 1})
	err = customerCollection.FindOne(ctx, bson.M{"age": 29}, findOptions).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({age: 29}, { name: 1, phone: true, \"address.postalCode\": 1}) | Result: ", commandResult)

	// Ignore properties
	findOptions = options.FindOne().SetProjection(bson.M{"name": false, "phone": 0, "address.city": 0})
	err = customerCollection.FindOne(ctx, bson.M{}, findOptions).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({}, { name: false, phone: 0, \"address.city\": 0}) | Result: ", commandResult)

	// Apply filter that doesn't return any result
	err = customerCollection.FindOne(ctx, bson.M{"age": 299999999}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({age: 299999999}) | Result: ", commandResult)

	// Use regex to filter by matching value of a field
	regexPattern := primitive.Regex{Pattern: "^alisa", Options: "i"}
	err = customerCollection.FindOne(ctx, bson.M{"name": bson.M{"$regex": regexPattern}}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result: ", commandResult)

	// Use regex
	regexPattern = primitive.Regex{Pattern: "drive", Options: "i"}
	err = customerCollection.FindOne(ctx, bson.M{"address.street": bson.M{"$regex": regexPattern}}).Decode(&commandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.findOne({\"address.street\": {$regex : /drive/i}}) | Result: ", commandResult)

	// Try to use findOne() one a non existing collection, We get null
	var wrongCommandResult bson.M
	err = wrongCollection.FindOne(ctx, nil).Decode(&wrongCommandResult)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.wrong_collection.findOne() | Result: ", wrongCommandResult)

}

Output:

Command: db.customer.insertMany() | Result:  &{[ObjectID("65c0a2d2945b344c8e8a3c63") ObjectID("65c0a2d2945b344c8e8a3c64") ObjectID("65c0a2d2945b344c8e8a3c65")]}

Command: db.customer.findOne() | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c63") 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.findOne({age: 29}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c65") address:map[city:Edmond postalCode:73025 state:OK street:632 Belmar Drive] age:29 name:Eloise Weber phone:618-357-2104]

Command: db.customer.findOne({age: {$gte: 29}}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c64") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054]

Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c63") 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.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c65") address:map[postalCode:73025] age:19 name:Eloise Weber phone:618-357-2104]

Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c63") address:map[postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Eloise Weber phone:618-357-2104]

mongo: no documents in result
Command: db.customer.findOne({age: 299999999}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c63") address:map[postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Eloise Weber phone:618-357-2104]

Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c64") address:map[city:Arvada postalCode:80003 state:CO street:8532 Ingalls Circle] age:72 name:Alisa Parker phone:768-319-1054]

Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result:  map[_id:ObjectID("65c0a2d2945b344c8e8a3c63") address:map[city:Pueblo West postalCode:81007 state:CO street:11 North Vineyard Drive] age:19 name:Izabella Conroy phone:108-679-2154]    

document is nil
Command: db.wrong_collection.findOne() | Result:  map[]

NOTES

  • Use the “FindOne()” method from “mongo-go-driver
  • Signature of the method-
    • FindOne(ctx, filter, options)
// db.collection.findOne() method example in Java

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class FindOne {

    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");
            MongoCollection<Document> wrongCollection = database.getCollection("wrong_collection");

            // 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 one document from cutomer collection
            Document findOneResult = customerCollection.find().first();

            System.out.println("Command: db.customer.findOne() | Result: " + findOneResult.toString());

            // Apply fitler where age=29
            findOneResult = customerCollection.find(Filters.eq("age", 29)).first();

            System.out.println(
                    "Command: db.customer.findOne({age: 29}) | Result: " + findOneResult.toString());

            // Apply filter where age >= 29
            findOneResult = customerCollection.find(Filters.gte("age", 29)).first();

            System.out.println(
                    "Command: db.customer.findOne({age: {$gte: 29}}) | Result: " + findOneResult.toString());

            // Use $or operator for the query filter
            findOneResult = customerCollection.find(Filters.or(Filters.gt("age", 29), Filters.eq("address.postalCode", "81007"))).first();

            System.out.println(
                    "Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {\"address.postalCode\": \"81007\"}]}) | Result: " + findOneResult.toString());

            // Set projection to get name, phone, and postalCode only
            findOneResult = customerCollection.find(Filters.eq("age", 29)).projection(new Document("name", 1).append("phone", true).append("address.postalCode", 1)).first();

            System.out.println("Command: db.customer.findOne({age: 29}, { name: 1, phone: true, \"address.postalCode\": 1}) | Result: " + findOneResult.toString());

            // Ignore properties
            findOneResult = customerCollection.find().projection(new Document("name", false).append("phone", 0).append("address.city", 0)).first();

            System.out.println("Command: db.customer.findOne({}, { name: false, phone: 0, \"address.city\": 0}) | Result:" + findOneResult.toString());

            // Apply filter that doesn't return any result
            findOneResult = customerCollection.find(Filters.eq("age", 299999999)).first();

            System.out.println("Command: db.customer.findOne({age: 299999999}) | Result: " + findOneResult);

            // Use regex to filter by matching value of a field
            Pattern pattern = Pattern.compile("^alisa", Pattern.CASE_INSENSITIVE);
            findOneResult = customerCollection.find(Filters.regex("name", pattern)).first();

            System.out.println(
                    "Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result: " + findOneResult.toString());

            // Use regex
            pattern = Pattern.compile("drive", Pattern.CASE_INSENSITIVE);
            findOneResult = customerCollection.find(Filters.regex("address.street", pattern)).first();

            System.out.println("Command: db.customer.findOne({\"address.street\": {$regex : /drive/i}}) | Result: " + findOneResult.toString());

            // Try to use findOne() one a non existing collection, We get null
            findOneResult = wrongCollection.find().first();

            System.out.println("Command: db.wrong_collection.findOne() | Result: " + findOneResult);

        }
    }
}

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=65c0adb3c6364f5e75ae469c}}, Document{{name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}, _id=65c0adb3c6364f5e75ae469d}}, Document{{name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}, _id=65c0adb3c6364f5e75ae469e}}]

Command: db.customer.findOne() | Result: Document{{_id=65c0adb3c6364f5e75ae469c, 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.findOne({age: 29}) | Result: Document{{_id=65c0adb3c6364f5e75ae469e, name=Eloise Weber, age=29, phone=618-357-2104, address=Document{{street=632 Belmar Drive, city=Edmond, state=OK, postalCode=73025}}}}

Command: db.customer.findOne({age: {$gte: 29}}) | Result: Document{{_id=65c0adb3c6364f5e75ae469d, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}

Command: db.customer.findOne({$or: [{age: {$gt: 29}}, {"address.postalCode": "81007"}]}) | Result: Document{{_id=65c0adb3c6364f5e75ae469c, 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.findOne({age: 29}, { name: 1, phone: true, "address.postalCode": 1}) | Result: Document{{_id=65c0adb3c6364f5e75ae469e, name=Eloise Weber, phone=618-357-2104, address=Document{{postalCode=73025}}}}

Command: db.customer.findOne({}, { name: false, phone: 0, "address.city": 0}) | Result:Document{{_id=65c0adb3c6364f5e75ae469c, age=19, address=Document{{street=11 North Vineyard Drive, state=CO, postalCode=81007}}}}

Command: db.customer.findOne({age: 299999999}) | Result: null

Command: db.customer.findOne({name: {$regex : /^alisa/i}}) | Result: Document{{_id=65c0adb3c6364f5e75ae469d, name=Alisa Parker, age=72, phone=768-319-1054, address=Document{{street=8532 Ingalls Circle, city=Arvada, state=CO, postalCode=80003}}}}

Command: db.customer.findOne({"address.street": {$regex : /drive/i}}) | Result: Document{{_id=65c0adb3c6364f5e75ae469c, 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.wrong_collection.findOne() | Result: null

NOTES

  • Use the method “find()” from MongoCollection. Then use the “first()” method to get the first result. There is no dedicated method for the findOne in the Java package.
  • 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-

Related Methods

CommandDetails
db.collection.find() 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

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.