MogoDB findAndModify返回WriteResult

问题描述 投票:1回答:2

我确实使用逻辑“如果不存在则插入”进行查询。我可以在没有其他查询的情况下返回上验证结果吗?

 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;
mongodb mongodb-query mongodb-.net-driver
2个回答
0
投票

使用new: true选项,请参阅4.0 release notes

Milestone.findOneAndUpdate({
    ......
}, {
    ......
}, {upsert: true, 'new': true}, function(err, res) {
    // err === null
    // res === null
    done(err, res);
});

0
投票

我会这样:

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的文档但未进行任何更改,您将得到:

enter image description here

如果存在具有该ID的文档,并且电子邮件已更改,您将得到:

enter image description here

最后,如果文档不存在并因此被添加,UpsertedId将显示其ID。

© www.soinside.com 2019 - 2024. All rights reserved.