Set the same value for multiple fields

I have the following document structure:

{
    ...
    timings: {
        mon: "",
        tue: "",
        wed: "",
        thu: "",
        fri: "",
        sat: "",
        sun: "",
    }
    ...
}

      

I want to set "Open 24 Hours" for all days of the week.

I am currently using query:

db.collection.update({_id: ObjectId("someId")}, {$set: {"timings.mon": "Open 24 Hours"}});

      

And then we will run the same for the rest of the week.

I can also set all fields in the same query explicitly, but it's faster to change the day and run it again.

Is there a way to set the value of multiple fields in a subdocument in a more efficient way?

UPDATE

I tried the following query but it doesn't work:

db.collection.update({_id: ObjectId("someId")}, {$set: {"timings.$": "Open 24 Hours"}});

      

+3


source to share


1 answer


You can try to create an update object first, where you can set multiple fields of that object before updating the document like this:

var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"],
    timings = {},
    query = {"_id" : ObjectId("554e12e4674dec7517e692eb")},
    update = {
        "$set": { "timings": timings }
    },
    options = {"upsert": true};

days.forEach(function (day){ timings[day] = "Open 24 Hours" });
db.collection.update(query, update, options);

      

Requesting a collection for this document with db.collection.findOne(query)

will give:

/* 0 */
{
    "_id" : ObjectId("554e12e4674dec7517e692eb"),
    "timings" : {
        "mon" : "Open 24 Hours",
        "tue" : "Open 24 Hours",
        "wed" : "Open 24 Hours",
        "thu" : "Open 24 Hours",
        "fri" : "Open 24 Hours",
        "sat" : "Open 24 Hours",
        "sun" : "Open 24 Hours"
    }
}

      

- UPDATE -



Another approach (as @Michael suggested in the comments) is to use an inline JavaScript method that returns an array of a given object of its own enumerated properties in the same order as in the for for ... in loop (the difference is that the for- in lists properties in the prototype chain): Object.keys()

> var days = Object.keys(db.collection.findOne().timings);
> print(days);
mon,tue,wed,thu,fri,sat,sun
>

      

And thus it can be implemented as:

var days = Object.keys(db.collection.findOne().timings),
    timings = {},
    query = {"_id" : ObjectId("554e12e4674dec7517e692eb")},
    update = {
        "$set": { "timings": timings }
    },
    options = {"upsert": true};

      

+4


source







All Articles