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

Slice.cs
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();

The same result can be achieved using a ProjectionDefinition.

var sliceProjection = Builders<Traveler>.Projection
    .Expression(u =>
    new
    {
        name = u.Name,
        visitedCountries = u.VisitedCountries.Take(1)
    });

var sliceProjectionResults = await travelersCollection
    .Find(Builders<Traveler>.Filter.Empty)
    .Project(sliceProjection)
    .ToListAsync();

Get last N elements

The following sample returns the Traveler documents but only the last 2 visited countries included.

Slice.cs
var sliceQueryTwoLastCountries = 
   from t in travelersQueryableCollection
   select new 
   { 
      t.Name, 
      visitedCountries = t.VisitedCountries.Take(-2) 
   };

var sliceQueryTwoLastCountriesResults = 
   await sliceQueryTwoLastCountries
   .ToListAsync();

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.

var travelersQueryableCollection = tripsDatabase
    .GetCollection<Traveler>(Constants.TravelersCollection)
    .AsQueryable();
    
var sliceWithSkipQuery = 
    from t in travelersQueryableCollection
    select new { 
        t.Name, 
        visitedCountries = t.VisitedCountries
                            .Skip(2).Take(3) };

var sliceWithSkipQueryResults = 
    await sliceQuery.ToListAsync();

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.

ComparisonOperators.cs
var travelersQueryableCollection = tripsDatabase
    .GetCollection<Traveler>(Constants.TravelersCollection)
    .AsQueryable();

var filterQuery = 
    from t in travelersQueryableCollection
    select new
    {
         t.Name,
         visitedCountries = t.VisitedCountries
                 .Where(c => c.TimesVisited == 1)
    };

var filterQueryResults = await filterQuery.ToListAsync();

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

{
    "_id" : 0,
    "item" : "Handmade Steel Shoes",
    "price" : 172,
    "quantity" : 3,
    "shipmentDetails" : {
        "shipAddress" : "547 Kris Hill, Dooleyville, Niger",
        "city" : "Port Caryport",
        "country" : "Northern Mariana Islands",
        "contactName" : "Keenan McDermott",
        "contactPhone" : "1-956-915-2404"
    }
}

The sample creates a projection stage to return the total for each order, with total=priceβˆ—quantitytotal = price * quantity

Multiply.cs
var ordersCollection = tripsDatabase
    .GetCollection<Order>(Constants.OrdersCollection);

var multiplyQuery = 
    from o in ordersCollection.AsQueryable()
    select new // creates a projection stage
    {
      o.OrderId,
      total = o.Quantity * o.Price // $multiply field
    };

var multiplyQueryResults = 
    await multiplyQuery.ToListAsync();

Last updated