What is the intended behavior of Datastore.save() when handed an Iterable of objects?

て烟熏妆下的殇ゞ 提交于 2020-01-06 05:47:05

问题


I am debugging a bizarre situation involving MongoDB and two programs.

The MongoDB installation in question is initially empty and is a toy deployment.

There are two programs. One uses Morphia. The other does not.

The non-Morphia-using program inserts a record into a Service collection in a foo-bar database like so:

mongo << EOF
db.getSiblingDB("foo-bar").getCollection("Service").replaceOne( {
  "service_name" : "argle-bargle"
}, {
  "_id" : "argle-bargle",
  "className" : "com.foo.Service",
  "service_name" : "argle-bargle",
}, {
  "upsert" : true
} )
EOF

The write is acknowledged:

MongoDB shell version v3.4.6
connecting to: mongodb://aura-mongodb:27017/
MongoDB server version: 3.4.6
{
    "acknowledged" : true,
    "matchedCount" : 0,
    "modifiedCount" : 0,
    "upsertedId" : "argle-bargle"
}
bye

The Morphia-using program does this:

final MongoClient client = // ...
final Morphia morphia = new Morphia();
morphia.mapPackage("com.foo");
final Datastore dataStore = morphia.createDatastore(client, "foo-bar");
assert dataStore != null;
dataStore.ensureIndexes();

…followed by:

final Collection<com.foo.Service> services = // ...collection of size 2...
this.dataStore.save(services);

There should now be three items in the database. There are not.

Connecting with mongo and getting ahold of the Service collection in the foo-bar database and issuing find() shows there to be two (the result of the Morphia-using program's operation).

I HOPE that if I had 20,000 records in that collection that a save(collectionOf2Items) would not delete 19,998 of them!

So then: is save destructive when handed an Iterable? Any other suggestions on how to debug this baffling problem are greatly appreciated.


回答1:


Hard to tell without any code but if the ID's of the items match calling save() will simply update the existing item.

From Morhpia Quick Tour

Updating data in MongoDB is as simple as updating your Java objects and then calling datastore.save() with them again.

Edit: For debugging it might be worthwhile to try manually setting the ID fields to an ID you know is not already in use.



来源:https://stackoverflow.com/questions/48160098/what-is-the-intended-behavior-of-datastore-save-when-handed-an-iterable-of-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!