Data Insertion
Single Document Insert
db.collection.insertOne({
name: "John Doe",
age: 30,
email: "john@example.com"
})
Batch Insert
Array batch insert:
db.collection.insert([
{name: "Document 1", value: 100},
{name: "Document 2", value: 200}
])
insertMany method:
db.collection.insertMany([
{_id: 1, title: "Article A"},
{_id: 2, title: "Article B"}
])
Comparison Operators
- $eq: Equal to
- $ne: Not equal to
- $gt: Greater than
- $gte: Greater than or equal to
- $lt: Less than
- $lte: Less than or equal to
Logical Queries
AND Conditions
db.collection.find({
key1: value1,
key2: value2
})
OR Conditions
db.collection.find({
$or: [
{age: {$lt: 20}},
{age: {$gt: 30}}
]
})
NOT Conditions
db.collection.find({
age: {$not: {$eq: 25}}
})
Application Examples
- Query users aged between 20-30:
db.users.find({age: {$gte: 20, $lte: 30}})
- Query users older than 25 or with income below 5000:
db.users.find({
$or: [
{age: {$gt: 25}},
{income: {$lt: 5000}}
]
})