我确实使用逻辑“如果不存在则插入”进行查询。我可以在没有其他查询的情况下返回上验证结果吗?
var u = Builders<Blog>.Update
.SetOnInsert(f => f.BlogId, blogId)
.SetOnInsert(f => f.VideoId, videoId)
-- other fields...
var blog = Blog.FindOneAndUpdate<Blog>(c => c.BlogId == blogId && c.VideoId == VideoId, u,
new FindOneAndUpdateOptions<Blog>{IsUpsert = true, ReturnDocument = ReturnDocument.After}
);
bool wasUpsert = ?
return wasUpsert;
使用new: true
选项,请参阅4.0 release notes。
Milestone.findOneAndUpdate({
......
}, {
......
}, {upsert: true, 'new': true}, function(err, res) {
// err === null
// res === null
done(err, res);
});
我会这样:
var filter = Builders<MyCollectionModel>.Filter
.Eq(x => x.Id, ObjectId.Parse("5ecd93f739a1c716ab2c2d44"));
var update = Builders<MyCollectionModel>.Update.Set(x => x.Email, "[email protected]");
var updateResult = await context.MyCollectionModel
.UpdateOneAsync(filter, update, new UpdateOptions {IsUpsert = true});
updateResult.Dump(); // LINQPad
然后,如果存在具有该ID的文档但未进行任何更改,您将得到:
如果存在具有该ID的文档,并且电子邮件已更改,您将得到:
最后,如果文档不存在并因此被添加,UpsertedId
将显示其ID。