UpdateOneModel replaces existing document in mongodb java-driver - mongodb

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.

Related

updating Map values in array flutter Firebase

here is the map and the vlaue im trying to update
the problem is when i try to update the imageUrl , the whole Map replacing with only ImageUrl new value
like this
what i want is to update imageUrl only , not effecting other data
this is what i do but not work
FirebaseFirestore.instance.collection('oorders').doc('MyDocId')
.update({ 'items.0.imageUrl' : 'new image Url' });
From the provided Firestore Database structure it is clear that you are trying to update an element inside an array field in a Firestore document. But currently Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.
So if you try to do something like the following -
FirebaseFirestore.instance
.collection('oorders')
.doc('MyDocId')
.update({'items.0.imageUrl': 'new image Url'});
it will delete the array element items and create another map named items with the field mentioned in the update statement.
As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.
I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -
By doing this you can update the nested objects by dot notation as mentioned here which will update only the mentioned field without deleting the other fields. The sample to update the document will look like this -
var item = 'item1';
var propertyToBeUpdated = 'imageUrl';
var newImageUrl = 'New image Url';
FirebaseFirestore.instance
.collection('collectionId')
.doc('documentId')
.update({'items.$item.$propertyToBeUpdated': newImageUrl});

Updating old entries on MongoDB

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"})

MongoDB Java Driver creating Database and Collection

i was testing how to create database and collection mongo java driver.
MongoClient client = new MongoClient("localhost",27017);
DB db = client.getDB("ow");
DBCollection collection = db.getCollection("documents");
collection.save(new BasicDBObject("_id",1));
collection.remove(new BasicDBObject("_id",1));
boolean result = db.collectionExists("documents");
assertTrue(result);
assertNotNull(collection);
client.close();
I would prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first document is inserted.
My question is is this understanding correct ? Is above code correct was of creating collection or database.
prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first
document is inserted.
MongoDB creates a collection implicitly when the first document is saved into a collection. The createCollection() method explicitly creates a collection only and only if an options object is passed to it as an argument.
Now this makes sense. The options parameter can take in one or more arguments to decide the characteristics of the collection we want to create such as capped,autoIndexId,size,usePowerOf2Sizes,max no. of documents.
If we do not specify any of these options, the default behavior would take precedence, i.e create a collection lazily whenever the first insert is made, with default settings.
So if we want a collection whose characteristics we are going to define, then we can pass these characteristics as a DBObject to the createCollections() method and our collection would be created. Below is an example of how to pass the options.
BasicDBObject options = new BasicDBObject();
options.put("size", 12121212);
db.createCollection("hello", options);
Is above code correct was of creating collection or database.
Yes. It allows mongodb to apply the default configuration for your collection. Unless you want to set the
max,size,autoIndexId,capped,usePowerOf2Sizes properties for your new collection, this is fine.
Refer: http://docs.mongodb.org/manual/reference/method/db.createCollection/

Inserting new data into a record in MongoDB

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.

How to move object from one collection to another without changing _id

I have a queue mechanism which I want to keep small, so all queued objects, after they are done processing are moved to a different collection called history, where they are not updated anymore and are only there for reference and info.
Is it possible to take an object from one collection, remove it and insert it into another collection without changing the _id ?
I now solved this by creating a second id in the schema which I transfer to the new object, but I'd rather keep referencing _id.
Also if you think I'm overlooking something and don't need a second collection to keep my queueing mechanism fast, I'd love to hear about it.
Here's how I currently do it (using step and underscore)
`
// moving data to a new process in the history collection
var data = _.omit(process.toObject(), '_id');
console.log("new history data", data);
var history = new db.History(data);
history.save(this.parallel());
db.Queue.remove({_id : process._id }, this.parallel());
`
You can copy/move a doc from one collection to another without changing its _id just fine. If you create a new doc that already has an _id then Mongoose/Mongo will use it. And _id values only need to be unique within a single collection, not between collections.
I tried using delete delete object._id; in order to remove the property and allow mongodb to assign one itself, but for some reason delete did not work.
This works for me:
obj['_id'] = undefined;
If you are not going to use the _id then this will fix your problem.