本文介绍了MongoDB 2.4的“更新后数组中的元素数量限制".使用C#驱动程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB 2.4添加了新的"Limit 更新后的数组中的元素数" .这是可以通过外壳使用的方式:

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
            }
        }
    }
)

如何使用MongoDB的C#驱动程序完成此操作?

推荐答案

下面是一个示例测试,显示了如何在不使用类型化类的情况下执行此操作: https://github.com/mongodb/mongo-csharp-driver/blob/master/MongoDB.DriverUnitTests/Builders/UpdateBuilderTests.cs#L492

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);

如果您使用类型化的实体,我们也支持此功能: https://github.com/mongodb/mongo-csharp-driver/blob/master/MongoDB.DriverUnitTests/Builders/UpdateBuilderTests.cs#L524

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 } });

最后,像.NET驱动程序中的所有其他内容一样,您始终可以构建一个与上面的结构完全相似的BsonDocument并简单地执行它.

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.

这篇关于MongoDB 2.4的“更新后数组中的元素数量限制".使用C#驱动程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:29