Home > Mobile >  Mongodb: how to update the latest field
Mongodb: how to update the latest field

Time:02-10

I am new to Mongodb. I have a collection of this form:

db.buckets.aggregate()

[
    {
        "_id": ObjectId("6202faa5eeaef7a5b1c974d6"),
        "bucket": "7835@0493",
        "ts": ISODate("2022-02-08T23:20:05.107Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    },
    {
        "_id": ObjectId("6202faaeeeaef7a5b1c974d7"),
        "bucket": "7805@0498",
        "ts": ISODate("2022-02-08T23:20:14.988Z"),
        "val": {"Wh1": 0, "Wh2": 0}
    }
]

......

I would like to update the fields Wh2 and Wh1 of the latest "bucket" : "7835@0493"

I tried the following :

db.buckets.findAndModify({query: {"bucket": "7835@2096"},sort: {ts:-1},update({"val": {"Wh1": 90,"Wh2": 50}})})

and got:

2022-02-09T20:28:34.834 0900 E QUERY [js] uncaught exception: SyntaxError: missing variable name : @(shell):1:99

any help is appreciated.

CodePudding user response:

From findAndModify docs, you miss out the update operator and also some syntax errors.

db.buckets.findAndModify({
    query: { "bucket": "7835@0493" },
    sort: { ts:-1 },
    update: { 
        $set: { 
            "val": {
                "Wh1": 90,
                "Wh2": 50
            }
        }
    }
})
  • Related