Search code examples
mongodbmongodb-.net-driver

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


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?


Solution

  • 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.