mongodb总结

2017-12-30  本文已影响102人  markdown

Q: 查询字段是否存在

db.collections.find({filed: {$exists: true}})

Q: 查询不存在字段field的数据并且设置字段为newValue

db.collections.updateMany({filed: {$exists: false}}, {$set: {filed: newValue}}

Q: 数据中存在知识点属性,该属性结构为

points: [
    {
      point: { // 最后一个知识点
        type: ObjectId,
        ref: 'point'
      },
      path: [String] // 知识点路径
    }
  ],

需要查询知识点a及知识点a之下所有知识点的数据

db.collections.find({
  points: {
  $elemMatch: {
       path: {
          $all: point // point为知识点a的path
        }
      }
  }
})

Q: 二维数组元素查询,结构为

{
  "a": [["yellow", "num"], ["blue", "num"]]
}

查出有’yellow’的数据

db.collections.find({'a':{'$elemMatch':{'$elemMatch':{'$in':['yellow']}}})

Q: 删除数据的属性filed

db.collections.updateMany({}, {$unset: {filed: 1}}

Q: 查询数据中数组大于n的数据

数组元素个数可以使用$size,如查询数组个数为n的数据:

db.collections.find({list: {$size: n}})

但是$size不能使用范围运算。可以使用$where关键字

db.collections.find({$where: "this.list.length > n"})

这种方法速度较慢,可以使用

db.collections.find({"list.n": {$exists: true}})

这种方法速度更快,但是前提是数组中的元素不能为空值。另外也有人添加size属性,专门用来保存数组长度,此时,查询size的大小即可。

Q: 删除数据中filed字段重复的数据

  1. 新建立一个new集合,用于保存去重后的数据。且再new集合中建立唯一索引
db.new.ensureIndex({"field":1},{"unique":true})
  1. 将old集合中的数据使用mongoexport导出,然后mongoimport导入到new集合中
mongoexport -d test -c old -o data.dat
mongoimport -d test -c new data.dat

Q: mongodb不联网无法连接

数据库地址使用127.0.0.1,而不使用localhost

参考:
数组相关查询
MongoDB查询(数组、内嵌文档和$where)
数据更新命令
查询命令

上一篇 下一篇

猜你喜欢

热点阅读