I'm trying to insert data collected from a html form into an existing document. These will all be new fields and these are a python dict. However when I perform the insert or update it seems to override the original data.
I initially store the data as:
self.settings['db'].userInfo.insert(userData)
Then performed the update/insert as:
self.settings['db'].userInfo.update({'_id':DBid},locData)
My record now just holds data for the latter update.
How can I keep the original data in the document and just add in new data later on?
EDIT
I was able to add new values into the document by:
self.settings['db'].userInfo.update({'_id':DBid},{"$set":userData})
I used the same dict as before now and used the $set operator. This appended the document with the new fields and thier values.
You should be doing another insert, not an update.
An update changes the original value... That's what it's designed to do, so another insert will add a new record to the collection.
To keep all the old fields of the document, and add some more use the Operator $set.
Related
List<WriteModel<Document>> updateList =
new ArrayList<WriteModel<Document>>(documents.size());
documents.stream().forEach((document) -> {
updateList.add(new UpdateOneModel<Document>(
new Document().append("accountNum",
document.get("accountNum")),
new Document().append("$set", document)));
});
BulkWriteResult result = securitiesCollection.bulkWrite(updateList,
MongoDbConstants.ORDERED_OPTION_FALSE);
In above code, Im trying to update subset of attributes in a document. After update I see whole document is replaced with just the subset. Is there a way to update a subset of attributes using bulkwrite operations using mongo-java-driver.
If you want to update some field only, don't set the whole object:
new Document().append("$set", document)));
Instead, set fields you need only:
new Document().append("$set", new BasicDBObject("field1",document.getField1()).append("field2", document.getField2());
UpdateOneModel updates as expected, I was infact populating null values to other attributes, thats the reason other attributes were getting updated to null.
I have some JSON entries in MongoDB but I plan to add new attributes into all my entries, like how you would create a new column and appoint a default value in RDBMS.
Is there any way to do it with MongoDB?
If you mean that every new document needs to be guaranteed to have the new fields, I'm afraid that it's not possible in MongoDB itself, because it is schemaless. I am however not familiar with mongoose, and there can be a solution using it.
If, like your title suggests, you just want to add the new fields to all existing documents you can do it with an update with empty filter like this:
db.collection.updateMany({}, {"newfield1":"val1","newfield2":"val2"})
While writing data to mongodb, we are checking if the data is present get the _id and using save update it else using insert add the data. Read save is the best way if you are providing _id in the query while saving it will update/insert based on if the _id is present in the db. Is the save the best method or is there any other way.
If you have all data available to save, just run update() each time but use the upsert functionality. Only one query required:
db.collection.update(
['_id' => $id],
$data,
['upsert' => true]
);
If your _id is generated by mongo you always know there is a record in the database and update is the one to use, but then again you could also save().
If you generated your id's (and thus don't know if it comes from the collection), this will always work without having to run an extra query.
From the documentation
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
db.collection.insert()
Inserts a document or documents into a collection.
If you use db.collection.insert() in your case you will get duplication key error since it will try to insert new document which has same _id with an existing document. But instead of using save you should use the update method.
In MongoDB, you can use db.collection.save({_id:'abc'}, objectToSave) to perform an upsert.
Let's define objectToSave as below
{_id:'abc', field1:1, field2:2};
In my collection, I have already have a document with same _id value as below:
{_id:'abc', field3:3};
The save function above will replace the existing document in collection to
{_id:'abc', field1:1, field2:2};
What I want is to perform a $set operation to produce some document in collection as below
{_id:'abc', field1:1, field2:2, field3:3};
Can this be achieved in the save function or I have to write separate update statements?
Note that objectToSave's fields are dynamic. The language I'm using is Node.JS.
db.collection.update({'_id':'abc'},{$set:{field1:1,field2:2}},{upsert:true})
should do what you want:
It upserts, so if the document does not exist yet, it is created as {_id:'abc',field1:1,field2:2} and efficiently so, since an index is used which must exist
If the document already exists, the fields field1 and field2 are set to the value in the update statement.
If either of the fields exist in the document, it will be overwritten.
Since you didn't state what language you use: in plain mongoDB, there is no save function. The explicit requirement to merge new and persisted versions of entities is quite an unusual one, so yes, I'd assume that you have to write a custom function.
I want to do a batch insert in mongodb , but if the record exists already it should replace it with the new one.There is update command but its not possible to do it in batch.Any idea whether it is possible? I am using java api.
Thanks
Edit:
As my collection size is not very huge, i am renaming the collection with drop Target option set to true and creating a new collection with this data.As i cant risk deleting and creating a new collection this is better, but it will be awesome if there is replace into equivalent.
If you are having any primary key in your collection, then it will replace automatically.Make sure your documents have _id key.
Look at mongodb document:
Shorthand for insert/update is save - if _id value set, the record is updated if it exists or inserted if it does not; if the _id value is not set, then the record is inserted as a new one.
in http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html