Search By Label
db.collection.find({ name: {$regex: "Match here"} })
find
method):db.collection.find({ description: { $exists: true, $ne: "" } })
$exists: true
: ensures the field exists.$ne: ""
: ensures the field is not an empty string.orders
with documents representing individual orders. Each document has fields like order_id
, customer_id
, product_name
, and price
. We want to calculate the average order value for each customer.db.orders.aggregate([ { $group: { _id: "$customer_id", total_spent: { $sum: "$price" }, total_orders: { $count: {} } } }, { $project: { average_order_value: { $divide: ["$total_spent", "$total_orders"] } } } ])
customer_id
.$sum
.$count
.total_spent
by total_orders
.customer_id
and the calculated average_order_value
.mongosh "mongodb+srv://{MONGO_COLLECTION_USER}:{MONGO_COLLECTION_PASSWORD}@{MONGO_APP_NAME}.yng1j.mongodb.net/?appName={MONGO_APP_NAME}"
// show databases show dbs // use database use <db_name> // show collections show collections // finally interact with them, for example db.users.findOne()
Date
.db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 3600 });
expiresAt
field and sets the TTL to 1 hour (3600 seconds). Any documents in the sessions
collection with an expiresAt
value that is older than 1 hour will be automatically deleted.explain("executionStats")
command in MongoDB provides detailed information about the execution plan and performance metrics of a query.find()
method, it returns a document containing statistics about how MongoDB executed the query.db.products.explain("executionStats").find({ price: { $gt: 10 } });
from
: The collection to use for lookup in the same databaselocalField
: The field in the primary collection that can be used as a unique identifier in the from
collection.foreignField
: The field in the from
collection that can be used as a unique identifier in the primary collection.as
: The name of the new field that will contain the matching documents from the from
collection.db.comments.aggregate([
{
$lookup: {
from: "movies",
localField: "movie_id",
foreignField: "_id",
as: "movie_details",
},
},
{
$limit: 1
}
])