Removing an array element in mongoDB based on element position

Actually I need to remove an element from the array based on its position. Using $ pop, we can remove an element from above or below (counting it as a stack. 0th element from above), as described here .

We can also remove an element from the array based on the value of the elements in the array using $ pull, as described here .

But I need to remove an element from the array based on position. So I can do it.

+4
source share
2 answers

From the documentation:

{ $pull : { field : {$gt: 3} } } removes array elements greater than 3 

So, suppose you can do something like this now:

 { $pull : { field : {$gt: 3, $lt: 5} } } // shoud remove elemet in 4 position 

Or try updating using the position operator , I think it will be something like this:

  { $pull : "field.4" } { $pull : {"field.$": 4}} 

This is just a suggestion because I cannot check it right now.

Update:

It seems you cannot know it correctly in one step (there is an error in jira )

But you can delete using an uninstalled element in position and display elements with a zero value:

 {$unset : {"array.4" : 1 }} {$pull : {"array" : null}} 
+7
source

Here is your MongoDB answer pull the array element from the collection

To remove a specific element from an array of some document, you first need to identify that element. For example, I have a document with an array, and each element of this array is an object:

  `{
     "_id": ObjectId ("5140f34888dd50971900002d"),
     "_permissions": {
         "edit": [
             {
                 "profile_id": NumberLong (123),
                 "comment": "app / project owner"
             },
             {
                 "profile_id": NumberLong ("153579099841888257"),
                 "comment": "project admin"
             },
             {
                 "profile_id": NumberLong ("153579095869882369"),
                 "comment": "project admin"
             }
         ],
         "view": [
             {
                 "profile_id": NumberLong (123),
                 "comment": "app / project owner"
             },
             {
                 "profile_id": NumberLong ("153579099841888257"),
                 "comment": "project admin"
             },
             {
                 "profile_id": NumberLong ("153579095869882369"),
                 "comment": "project admin"
             }
         ]
     }
 } `

So, let's remove "profile_id" with "153579099841888257" from the _permissions.view array. Here we go

 `db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});` 
  • I define the scope of the object (to make sure the identifier does not affect any other document found)
  • Define the required output element: "profile_id" with the value "153579099841888257" in the _permissions.view array
0
source

Source: https://habr.com/ru/post/1339367/


All Articles