Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull all elements from array in MongoDB without any condition

I have a document as below, and I want to pull all the elements in this array without any condition just via one statement. how can I do?

    "energy_sent" : [ 
        {
            "player_id" : "034010000093",
            "_id" : ObjectId("53675b8d251c20490d9679c6"),
            "time" : ISODate("2014-05-05T09:36:13.629Z"),
            "has_accepted" : 0,
            "energy_value" : 2
        }, 
        {
            "player_id" : "034010000094",
            "_id" : ObjectId("53675cfa251c20490d9679cc"),
            "time" : ISODate("2014-05-05T09:42:18.015Z"),
            "has_accepted" : 0,
            "energy_value" : 2
        }, 
        {
            "player_id" : "034010000116",
            "_id" : ObjectId("5367767889f8e3ee137dd239"),
            "time" : ISODate("2014-05-05T11:31:04.457Z"),
            "has_accepted" : 0,
            "energy_value" : 2
        }
    ]
like image 722
Hunter Zhao Avatar asked May 06 '14 11:05

Hunter Zhao


People also ask

How do I pull all elements in an array in MongoDB?

The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.

How do I retrieve an array in MongoDB?

MongoDB query array operator is used to query documents with an array, we can retrieve array element of data by using query array operator in MongoDB. There are three types of query array operators available in MongoDB, we need to use prefix as $ sign before using query array operator.

How get all items from MongoDB?

To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.

What does $all do in MongoDB?

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.


1 Answers

If you are just after emptying the entire array just set it to empty:

db.collection.update(
   { /* query to match document */ },
   { "$set": { "energy_sent": [] }
)

So just use the $set operator

like image 197
Neil Lunn Avatar answered Nov 15 '22 08:11

Neil Lunn