MongoDB比我想起的要难!我已经尝试了各种版本的if-exists-replace-else-insert以及各种功能和选项。它应该很容易,不是吗?使用MongoDB .Net驱动程序查找POCO
这是我个人认为,以下应该工作。
var collection = storageClient.GetCollection<Observer>("observers");
await collection.Indexes.CreateOneAsync(Builders<Observer>.IndexKeys.Ascending(_ => _.MyId), new CreateIndexOptions { Unique = true });
foreach (var observer in _observers)
{
observer.Timestamp = DateTime.Now;
var res = await collection.FindAsync(o => o.MyId == observer.MyId);
if (res==null ||res.Current == null) {
await collection.InsertOneAsync(observer); //Part 1, fails 2nd time solved with res.MoveNextAsync()
}
else
{
observer.ID = res.Current.Single().ID;
var res2 = await collection.ReplaceOneAsync(o=>o.MyId==observer.MyId, observer);
var res3 = await collection.FindAsync(o => o.MyId == observer.MyId);
await res3.MoveNextAsync();
Debug.Assert(res3.Current.Single().Timestamp == observer.Timestamp); //Part 2, Assert fails.
}
}
观察看起来大约是这样的:
public class Observer : IObserver
{
[BsonId]
public Guid ID { get; set; }
public int MyId { get; set; }
public DateTime Timestamp { get; set; }
}
我使用完全相同的集合运行此第二次,我意外地得到:
E11000 duplicate key error index: db.observers.$MyId_1 dup key: { : 14040 }
编辑:
新增原第二部分代码:替换。
编辑2:
现在我的代码看起来像这样。仍然失败。
var collection = storageClient.GetCollection<Observer>("gavagai_mentions");
await collection.Indexes.CreateOneAsync(Builders<Observer>.IndexKeys.Ascending(_ => _.MyID), new CreateIndexOptions { Unique = true });
foreach (var observer in _observers)
{
observer.Timestamp = DateTime.Now;
// Create a BsonDocument version of the POCO that we can manipulate
// and then remove the _id field so it can be used in a $set.
var bsonObserver = observer.ToBsonDocument();
bsonObserver.Remove("_id");
// Create an update object that sets all fields on an insert, and everthing
// but the immutable _id on an update.
var update = new BsonDocument("$set", bsonObserver);
update.Add(new BsonDocument("$setOnInsert", new BsonDocument("_id", observer.ID)));
// Enable the upsert option to create the doc if it's not found.
var options = new UpdateOptions { IsUpsert = true };
var res = await collection.UpdateOneAsync(o => o.MyID == observer.MyID,
update, options);
var res2 = await collection.FindAsync(o => o.MyID == observer.MyID);
await res2.MoveNextAsync();
Debug.Assert(res2.Current.Single().Timestamp == observer.Timestamp); //Assert fails, but only because MongoDB stores dates as UTC, or so I deduce. It works!!
}
对于未来的读者来说,文档是在这里:http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/#finding-documents –
克雷格谢谢!这实际上很有帮助。这些日子很难在StackOverflow上获得帮助。如果可以的话,请查看第二部分。 http://stackoverflow.com/questions/32586064/replace-poco-with-mongodb-net-driver-2 – Martin
你想要做的事应该能够通过['UpdateOneAsync'](http:/ /api.mongodb.org/csharp/current/html/M_MongoDB_Driver_IMongoCollection_1_UpdateOneAsync.htm?_ga=1.73733265.2070706799.1441907109)与upsert选项来创建文档,如果它没有找到。这样你可以做到这一点原子。你看过吗?你可以将它作为所有字段的“$ set”来构造,以便它能够有效地替换文档(如果找到的话)。 – JohnnyHK