MongoDB query notes

2017-08-26  本文已影响0人  一斤蔬菜
collection.find()
collection.findOne() //返回一条

无条件查询:

db.collection.find()
//SELECT * FROM tables;

(多)条件查询

db.collection.find({"key":"value"})

SELECT * FROM tables WHERE key='value';

条件操作符

{"key":{"$lt":100}}
{"key":{"$in":[100,200]}}
{"key":{"$mod":[10,1]}}

与或非

{"$or":[{"key1": "value1", "key2":"value2"}},{"key":{"$in":[100,200]}]}

其他

复杂的查询,$where当然是非常方便的,但效率低下。对于复杂查询,考虑的顺序应当是 正则 -> MapReduce -> $where

//document:
//{"key:["value1", "value2", "value3" ] }
db.collection.find({"key":{"$size":3}},{"key":{"$slice":1}})
//通过$size查询数组个数为3的数据,返回前1条.

this

db.collection.find({"$where":"this.key1>this.key2"})

js

$语句支持通过js函数返回值进行查询.
{"$where":"function () { return this.a == this.b}"}

$elemMatch

元素为数组,切数组的元素为K-V形式时使用.

{"key":{"$elemMatch":{"key2":"value"}}}
上一篇 下一篇

猜你喜欢

热点阅读