MongoDB c#驱动程序FindAndModify

本文关键字:FindAndModify 驱动程序 MongoDB | 更新日期: 2023-09-27 18:10:22

我试图在MongoDB中运行FindAndModify操作,但我得到了一个不寻常的异常

var query = Query.EQ("_id", wiki.ID);
var sortBy = SortBy.Descending("Version");
var update = Update.Set("Content", wiki.Content)
                    .Set("CreatedBy", wiki.CreatedBy)
                    .Set("CreatedDate", wiki.CreatedDate)
                    .Set("Name", wiki.Name)
                    .Set("PreviousVersion", wiki.PreviousVersion.ToBsonDocument())
                    .Set("Title", wiki.Title)
                    .Set("Version", wiki.Version);
var result = collection.FindAndModify(query, sortBy, update, true);

得到的异常是

WriteStartArray can only be called when State is Value, not when State is Initial
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: WriteStartArray can only be called when State is Value, not when State is Initial
Source Error:
Line 45:                 var query = Query.EQ("_id", wiki.ID);
Line 46:                 var sortBy = SortBy.Descending("Version");
Line 47:                 var update = Update.Set("Content", wiki.Content)
Line 48:                                    .Set("CreatedBy", wiki.CreatedBy)
Line 49:                                    .Set("CreatedDate", wiki.CreatedDate)

想法吗?我已经在mongodb的网站上实现了这个API。

编辑—固定每个@jeffsaracco

var update = Update.Set("Content", wiki.Content)
.Set("CreatedBy", wiki.CreatedBy)
.Set("CreatedDate", wiki.CreatedDate)
.Set("Name", wiki.Name)
.PushAllWrapped<WikiHistory>("PreviousVersion", wiki.PreviousVersion)
.Set("Title", wiki.Title)
.Set("Version", wiki.Version);

MongoDB c#驱动程序FindAndModify

您的PushAllWrapped解决方案可能是您想要的,也可能不是您想要的。它与Set不同,因为它将新值附加到当前数组值。如果你想用新的数组值替换现有的数组值,你可以使用这个版本的Set:

var update = Update.Set("Content", wiki.Content)
    // other lines
    .Set("WikiHistory", new BsonArray(BsonDocumentWrapper.CreateMultiple(wiki.PreviousVersion);

表示:将WikiHistory元素的值设置为一个新的BsonArray,该BsonArray是通过序列化PreviousVersion自定义类型的包装值构造的。

其中一列是数组类型吗?如果是,您可能需要调用

Update.Push

Update.PushAll

,如果PreviousVersion已经是一个BsonDocument,你可能不需要再次转换

您确定您的SortBy。下行吗?

api没有说明你可以使用string[]以外的东西作为参数(http://api.mongodb.org/csharp/current/html/96408b4e-c537-0772-5556-6f43805dd4d4.htm)

最后,因为我只是在跟踪对象的历史记录,所以我最终使用.AddToSetWrapped<WikiHistory>("PreviousVersion", CurrentVersion),它只是将项目附加到对象的集合中。