MongoDB 2.4's “Limit Number of Elements in an Array after an Update” using C# driver?

一曲冷凌霜 提交于 2019-12-08 02:58:27

问题


MongoDB 2.4 added a new "Limit Number of Elements in an Array after an Update" feature. This is how it can be used through the shell:

db.students.update(
    { _id: 1 },
    { $push: 
        { scores:
            { $each : 
            [
                { attempt: 3, score: 7 },
                { attempt: 4, score: 4 }
            ],
            $sort: { score: 1 },
            $slice: -3
            }
        }
    }
)

How can this be accomplished with the MongoDB's C#-driver?


回答1:


Here is an example test that shows how to do this without using typed classes: https://github.com/mongodb/mongo-csharp-driver/blob/master/MongoDB.DriverUnitTests/Builders/UpdateBuilderTests.cs#L492

The relevant piece of code you are looking for is this:

var update = Update.PushEach(
    "name", 
     new PushEachOptions { Slice = -3, Sort = SortBy.Descending("a") }, 
    value1ToPush, 
    value2ToPush);

We also support this if you are using typed entities: https://github.com/mongodb/mongo-csharp-driver/blob/master/MongoDB.DriverUnitTests/Builders/UpdateBuilderTests.cs#L524

var update = Update<Test>.PushEach(
    x => x.B, 
    args => args.SortDescending(x => x.C).Slice(-3), 
    new[] { new B { C = 0 }, new B { C = 1 } });

Finally, like everything else in the .NET driver, you can always build up a BsonDocument that looks exactly like your structure above and simply execute it.



来源:https://stackoverflow.com/questions/15787498/mongodb-2-4s-limit-number-of-elements-in-an-array-after-an-update-using-c-sha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!