Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove null element from mongo array

{
        "_id" : 160,
        "info" : [
            {
                'name': 'Serg',
                'proff': 'hacker'
            },
            null,
        ]
    }

As you can see I have null element in my array, I need a general solution that will remove null elements from info array.

I tried this:

for doc in iter:
    people.update({ '_id' : doc['_id']}, { '$pull' : { 'info' : 'null' }})

where iter is a collection of documents. and people is a collection

I also tried this in the shell:

> db.people.findAndModify({ query: {}, update: {'$pull': {info:null} } } )

But none of the above examples delete this null from my documents!! ))

like image 742
Vor Avatar asked Feb 11 '13 04:02

Vor


People also ask

How do you remove null values from an array in MongoDB?

You could remove all null elements from the array with the $pull operation. In the $pull condition you have to set the value that should be removed from the array not the index. So in you're case {$pull:{province:null}} . NOTE: This removes ALL null values from the array.

How do I remove an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I ignore NULL values in MongoDB?

Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .

How to delete first element of array MongoDB?

The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.


1 Answers

This should work out for you. In python null is called None.

    for doc in iter:
        people.update({'_id':doc[id]},{'$pull':{'info':None}})

null object in Python?

Also in mongo shell, this should work out:

    db.people.update({_id:160},{$pull:{info:null}})

If you want the update operator, to update more that one document at a time, that is to pull out null values from multiple documents, then you have to supply the multi:true option. Because by default, if the query arguemnt is left blank i.e. {} and mulit:true is not provided, update operator works on the first document that it finds

    db.people.update({},{$pull:{info:null}},{multi:true})
like image 116
ann Avatar answered Oct 11 '22 08:10

ann