总结了一下自己经常用到的一些MongoDB查询。
db.collection.find()
// SELECT * FROM xxx
db.collection.find( { <field1>: <value1>, ... } )
// SELECT * FROM xxx WHERE field1 = value1
db.collection.find( { <field1>: <value1>, ... }, { <field1>: 1, <field2>: 0, ... } )
// SELECT _id, field1 FROM xxx WHERE field1 = value1
db.collection.find( { <field1>: { $lt: <value1> } } )
//SELECT * FROM xxx WHERE field1 < value1
//Besides $lt, other commmon comparison operators is $lte, $gt, $gte, $in, $nin, $neq
db.collection.find( { $or: [ { <condition1> }, { <condition2> }, ... ] } )
//SELECT * FROM xxx WHERE condition1 OR <condition2
db.collection.findOne()
//SELECT * FROM xxx LIMIT 1
//When there is sub-field, use dot notation like "field.subfield" to access it
db.collection.find( { ... } ).count()
//SELECT COUNT(1) FROM xxx WHERE ...
db.collection.distinct(field, query, options)
//SELECT DISTINCT field FROM xxx WHERE ...
db.collection.dataSize()
//Calculate the size of the dump BSON file
db.collection.aggregate( [
{ $match: {...} },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
] )
//SELECT cust_id, SUM(amount) AS total
//FROM xxx
//WHERE ...
//GROUP BY id
//More abount Aggregation: https://docs.mongodb.com/manual/aggregation/
- Reference: MongoDB Documentation