问题
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