How to delete n-th element of array in mongodb

前端 未结 4 420
死守一世寂寞
死守一世寂寞 2020-12-05 14:45

For example I have this document:

db.test.save({
  _id: 1,
  list: [
    { key: \"a\" },
    { key: \"b\" },
    { key: \"c\" },
    { key: \"d\" },
    { ke         


        
相关标签:
4条回答
  • 2020-12-05 15:03

    No, unfortunately what you are doing is currently the best option. Have a look at this question: In mongoDb, how do you remove an array element by its index which links to a Jira for this very issue.

    0 讨论(0)
  • 2020-12-05 15:07

    Not at the current time. As it was answered in There is no straight way of pulling/removing by array index.

    There is an open issue asking for that operation, even though this workaround is ok, notwithstanding it is not an atomic solution.

    0 讨论(0)
  • 2020-12-05 15:14

    Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.

    For instance, in order to update an array by removing an element at a given index:

    // {
    //   "_id" : 1,
    //   "list" : [
    //     { "key" : "a" },
    //     { "key" : "b" },
    //     { "key" : "c" },
    //     { "key" : "d" },
    //     { "key" : "e" }
    //   ]
    // }
    db.collection.aggregate(
      { $set:
        { "list":
          { $function: {
              body: function(list) { list.splice(2, 1); return list; },
              args: ["$list"],
              lang: "js"
          }}
        }
      }
    )
    // {
    //   "_id" : 1,
    //   "list" : [
    //     { "key" : "a" },
    //     { "key" : "b" },
    //     { "key" : "d" },
    //     { "key" : "e" }
    //   ]
    // }
    

    $function takes 3 parameters:

    • body, which is the function to apply, whose parameter is the array to modify. The function here simply consists in using splice to remove 1 element at index 2.
    • args, which contains the fields from the record that the body function takes as parameter. In our case "$list".
    • lang, which is the language in which the body function is written. Only js is currently available.
    0 讨论(0)
  • 2020-12-05 15:24

    if you know the value which you want to remove

    db.test.update({{_id: 1},{"$pull" : {"list" : { "key" : "c"}}},false,false)
    

    more info at

    http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

    0 讨论(0)
提交回复
热议问题