从mongodb中的数组中删除元素 [英] Remove element from array in mongodb

查看:710
本文介绍了从mongodb中的数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mongodb的新手,我想删除数组中的某些元素.

I am new in mongodb and i want to remove the some element in array.

我的文档如下

{
  "_id" : ObjectId("4d525ab2924f0000000022ad"), 
  "name" : "hello", 
  "time" : [
      {
              "stamp" : "2010-07-01T12:01:03.75+02:00",
              "reason" : "new"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+03:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+04:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+05:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+06:00",
              "reason" : "update"
      }
  ]
}

在文档中,我要删除第一个元素(原因:新)和最后一个元素(06:00).

in document, i want to remove first element(reason:new) and last element(06:00) .

我想使用mongoquery做到这一点,我没有使用任何Java/php驱动程序.

and i want to do it using mongoquery, i am not using any java/php driver.

推荐答案

如果我对您的理解正确,那么如果数组的大小大于3,则要删除数组的第一个和最后一个元素.可以通过使用findAndModify查询来做到这一点.在mongo shell中,您将使用以下命令:

If I'm understanding you correctly, you want to remove the first and last elements of the array if the size of the array is greater than 3. You can do this by using the findAndModify query. In mongo shell you would be using this command:

db.collection.findAndModify({
    query: { $where: "this.time.length > 3" },
    update: { $pop: {time: 1}, $pop: {time: -1} },
    new: true
});

这将在您的集合中找到与$ where子句匹配的文档. $ where字段允许您指定任何有效的javascript方法.请注意,它仅将更新应用于第一个匹配的文档.

This would find the document in your collection which matches the $where clause. The $where field allows you to specify any valid javascript method. Please note that it applies the update only to the first matched document.

您可能还希望查看以下文档:

You might want to look at the following docs also:

  1. http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D 有关$ where子句的更多信息.
  2. http://www.mongodb.org/display/DOCS/正在更新#Updating-%24pop 有关$ pop的更多信息.
  3. http://www.mongodb.org/display/DOCS/findAndModify+Command 了解更多 在findAndModify上.
  1. http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D for more on the $where clause.
  2. http://www.mongodb.org/display/DOCS/Updating#Updating-%24pop for more on $pop.
  3. http://www.mongodb.org/display/DOCS/findAndModify+Command for more on findAndModify.

这篇关于从mongodb中的数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆