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

狂风中的少年 提交于 2019-12-06 07:28:47

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.

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