简体   繁体   中英

Java Mongodb update Database Object

I work with upload data that is stored in one collection. The data contains information about the upload date as an integer value so I want to create one Object in the collection that holds all the days when data was uploaded. This object of courase has to be updated with every upload in case the data was recorded on a new day. If there is already data available at the same day, the object does not have to be updated. The object is build the following:

{
"Content" : "UploadDates",
"value" : [123,456]
}

and the value JSONArray should be updated. Is there a more elegant way than taking the while object, merge the date array with the new dates and insert the whole object again?

EDIT: I implement in Java/Spring 2.1.4 Release and mongodb driver 3.8.2

You can use the $push update operation to push a new value into an array.

For example in the mongo shell:

> db.test.find()
{
  "_id": 0,
  "value": [
    123,
    456
  ]
}

Updating the document with $push :

> db.test.update({_id: 0}, {$push: {value: 789}})
WriteResult({
  "nMatched": 1,
  "nUpserted": 0,
  "nModified": 1
})

The new value is added to the tail end of the array:

> db.test.find()
{
  "_id": 0,
  "value": [
    123,
    456,
    789
  ]
}

If the array field doesn't exist, $push will create the field.

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