panjianm 发表于 2018-10-25 09:53:28

mongodb 数组操作

  mongoDB数组操作器
  $push会向数组末尾加入一个元素,如果数组不存在,则会创建这个数组。
  增加评论comments:
  db.blog.posts.update({"title":"a blog post"}
  ,{
  $push:
  {"comments":{"name":"joe","email":"joe@example.com"}}
  }
  )
  最终的结果是:
  {
  "_id":ObjectId("8df8df78d7f7d8df7"),
  "title":"a blog post"
  "comments":[{
  "name":"joe",
  "email":"joe@example.com"
  }]
  }
  $ne如果一个值不在数组里面,就加进去:
  db.papers.update({"authors cited":{"$ne":"richie"}},
  {$push:{"authors cited":"richie"}})
  也可以用$addToSet完成同样的功能:
  db.papers.update({"_id":ObjectId("sdf9sd7f67df89d")},
  {"$addToSet":{"authors cited":"richie"}})
  $addToSet和$each组合起来,可以添加多个不同的值:
  db.papers.update({"_id":ObjectId("sdf9sd7f67df89d")},
  {"$addToSet":{"authors cited":{"$each":["richie","dff","dsf"]}}})
  $pop删除数组中的元素:
  删除末尾的元素:{$pop:{key:1}}
  删除头部的元素:{$pop:{key:-1}}
  $pull基于特定条件删除元素:
  db.lists.insert({"todo":["dishes","laundry","dry cleaning"]})
  db.lists.update({},{"$pull":{"todo":"laundry"}})
  修改数组元素的数量:
  {
  "_id":ObjectId("df89d8fd7d"),
  "content":"...",
  "comments":[
  {
  "comment":"good post",
  "author":"joy",
  "votes":0
  },
  {
  "comment":"good post",
  "author":"joyn",
  "votes":0
  },
  {
  "comment":"good post",
  "author":"andy",
  "votes":0
  }
  ]
  }
  如果想增加第一个评论的投票数量:
  db.blog.update("post":post_id},{"$inc":{"comments.0.votes"}:1})
  修改用户名:($用于定位已匹配的的元素,如果多个,就匹配第一个)
  db.blog.update({comments.author:"andy"}:{"$set":{"comments.$.author":"jim"}})

页: [1]
查看完整版本: mongodb 数组操作