Slice with Projection with C#

2019-03-01 10:38发布

问题:

Is there any way to implement a slice along with a projection in just one query using the c# driver? Below is what i am trying to achieve using c#, but im stuck, can anyone help me out wit it?

db.employee.find({"employeeId": "999"}, { "empActivity" : { "$slice": -1 } }, {"employeeId": 1, "empActivity.transId": 1, _id: 0})

Note : empActivity is a an array containing nested documents, my query above works perfectly via the mongo shell but i am not able to figure out its equivalent in C#.

回答1:

There is a way to do this with the C# driver. Methods can be chanined on builders, so all of .Slice() and .Include()and .Exclude()

var fields = Fields.Slice("empActivity", -1)
    .Include("employeeId", "empActivity.transId")
    .Exclude("_id");

var cursor = collection.Find(query).SetFields(fields);