β¨Operators
Slice operator - $slice
The $slice operator is used to return a subset of an array. The Enumerable.Take method can be used to create a $slice operation on a array field.
Method call
Description
Take(1)
Returns the first element
Take(N)
Returns the first N elements
Take(-1)
Returns the last element
Take(-N)
Returns the last N elements
Get first N elements
The sample returns Traveler documents but only include the first element of their VisitedCountries array field.
var travelersQueryableCollection = tripsDatabase
.GetCollection<Traveler>(Constants.TravelersCollection)
.AsQueryable();
var sliceQuery = from t in travelersQueryableCollection
select new {
t.Name, visitedCountries =
t.VisitedCountries.Take(1) // slice here
};
var sliceQueryResults = await sliceQuery.ToListAsync();db.travelers.aggregate()
.project(
{
name: 1,
visitedCountries : {
$slice: ["$visitedCountries", 1]
}
})
-------------------
// sample result
{
"_id" : ObjectId("5e9d705b45359358b426065f"),
"name" : "Leopoldo Lueilwitz",
"visitedCountries" : [ // only one item
{
"name" : "Malta",
"timesVisited" : 9,
"lastDateVisited" : ISODate("2017-12-19T21:22:35.607+02:00"),
"coordinates" : {
"latitude" : 79.2858,
"longitude" : 13.7049
}
}
]
}The same result can be achieved using a ProjectionDefinition.
Get last N elements
The following sample returns the Traveler documents but only the last 2 visited countries included.
Pagination
Slice can be combined with the Skip method and provide full pagination functionality. The following sample skips the first 2 VisitedCountries array elements and returns the next 3.
Filter operator - $filter
The $filter operator is used to match and return array elements that fulfill the specified condition. The Enumerable.Where method can be used to create the condition.
The sample returns Traveler documents with their VisitedCountries array field containing only the countries that have been visited once.
Multiply operator - $multiply
The $multiply operator is used to multiply numbers and return the result. The operator can be used with both raw and field values.
Assuming a collection contains Order documents in the following format...
The sample creates a projection stage to return the total for each order, with
Last updated