MongoDB常用查询

总结了一下自己经常用到的一些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/   

Contents


本站采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议

知识共享许可协议