数据添加

单条数据插入

db.collection.insertOne({
  name: "John Doe",
  age: 30,
  email: "john@example.com"
})

批量添加

数组批量插入

db.collection.insert([
  {name: "文档1", value: 100},
  {name: "文档2", value: 200}
])

insertMany方法

db.collection.insertMany([
  {_id: 1, title: "文章A"},
  {_id: 2, title: "文章B"}
])

比较操作符

  1. $eq:等于
  2. $ne:不等于
  3. $gt:大于
  4. $gte:大于等于
  5. $lt:小于
  6. $lte:小于等于

逻辑查询

AND条件

db.collection.find({
    key1: value1,
    key2: value2
})

OR条件

db.collection.find({
    $or: [
        {age: {$lt: 20}},
        {age: {$gt: 30}}
    ]
})

NOT条件

db.collection.find({
    age: {$not: {$eq: 25}}
})

应用示例

  1. 查询年龄在20-30岁之间的用户:
db.users.find({age: {$gte: 20, $lte: 30}})
  1. 查询年龄大于25岁或者收入低于5000的用户:
db.users.find({
    $or: [
        {age: {$gt: 25}},
        {income: {$lt: 5000}}
    ]
})