You are viewing a single comment's thread from:

RE: Mongodb数据库快速开发

in #starnote • 13 hours ago

查询操作(find)详解 |
mongodb查询大全

查询
第一个大括号封装以什么样作为条件查询;
第二个大括号封装查询结果返回那些字段。

更改
第一个大括号封装一什么样的条件更改;
第二个大括号封装将那些字段更改为什么样的数据。
注意:封装的条件写法都一样,不管是CRUD操作,更改的都是一样的。这里所指的条件就类似于sql语句中的where条件。

// 这么写可以获取所有 name 为 "Fluff" 开头的数据
Kitten.find({ name: /^fluff/ }, callback);

// With a JSON doc
Person.
  find({
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    likes: { $in: ['vaporizing', 'talking'] }
  }).
  limit(10).
  sort({ occupation: -1 }).
  select({ name: 1, occupation: 1 }).
  exec(callback);

// Using query builder
Person.
  find({ occupation: /host/ }).
  where('name.last').equals('Ghost').
  where('age').gt(17).lt(66).
  where('likes').in(['vaporizing', 'talking']).
  limit(10).
  sort('-occupation').
  select('name occupation').
  exec(callback);


const doc = await Person.findOne();
const idString = doc._id.toString();
// Finds the `Person`, because Mongoose casts `idString` to an ObjectId
const queryRes = await Person.findOne({ _id: idString });
// Does **not** find the `Person`, because Mongoose doesn't cast aggregation
// pipelines.
const aggRes = await Person.aggregate([{ $match: { _id: idString } }]);