美文网首页
MongoDB query notes

MongoDB query notes

作者: 一斤蔬菜 | 来源:发表于2017-08-26 01:30 被阅读0次
collection.find()
collection.findOne() //返回一条
  • 基础

无条件查询:

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

(多)条件查询

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

SELECT * FROM tables WHERE key='value';

条件操作符

  • $lt
  • $lte
  • $gt
  • $gte
  • $ne
  • $in 包含
  • $all 全部包含
  • $nin 不含
{"key":{"$lt":100}}
{"key":{"$in":[100,200]}}
  • $mod 余数
{"key":{"$mod":[10,1]}}

与或非

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

其他

  • $where 用于复杂语句查询,不过他人评价效率较低,不推荐使用.

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

  • $slice 对包含数组的查询结果进行切片.
//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"}}}

相关文章

网友评论

      本文标题:MongoDB query notes

      本文链接:https://www.haomeiwen.com/subject/vrbsdxtx.html