简体   繁体   中英

How to push a document to a MongoDB set of documents which is unique by one field?

I have the following document in mongodb:

db.reports.insert({
    selection_type: "views",
    selection_value: "desktop",
    chart_points: [
        {
            date: "2018-01-01",
            value: 1831
        },
        {
            date: "2018-01-02",
            value: 0
        }
    ]
})

And I want to insert or update an item from chart_points based on date . I try to use $addToSet but that will create a new item in array.

Expected result:

{
    date: "2018-01-02",
    value: 2053
}

Result after I use $addToSet :

{
    date: "2018-01-02",
    value: 0
},
{
    date: "2018-01-02",
    value: 2053
}

I get that result after I run this query:

db.reports.update(
    {},
    {
        $addToSet: {
            chart_points: {
                date: "2018-01-03",
                value: 1876
            }
        }
    }
)

NOTE: I have only that document in collection.

You will need two statements. You can use the positional operator in the $set to update when the date exists.

db.reports.update(
    { "chart_points.date": "2018-01-02" }, 
    { 
        $set: {
            "chart_points.$.value": 2053
        }
    }
)  

Adding a $ne check in the query document will prevent the $addToSet from inserting when the date already exists.

db.reports.update( 
    { "chart_points.date": { $ne: "2018-01-02"}}, 
    { 
        $addToSet: {
            chart_points: {
                date: "2018-01-02",
                value: 2053
            }
        }
    }
);

You can run these back-to-back to get the insert/update functionality you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM