How to combine Aggregate function with update

Viewed 15

I could not find a way to translate the fowling MongoDb command into C#

db.Queue.aggregate( 
[ 
   { $match: { "Processed": false } }, 
   { $sort: { "LastTimeChanged": 1  } }, 
   { $limit: 1 }, 
   { $set: { "WorkerName": "WORKER_NAME", "Processed": true }  }, 
   { "$merge": "Queue"  }])

The issues that I fund was with the $set and $merge command

  • $set -> in the MongoDb.Driver for .NET, associated with the Aggregate command I could not find any command that look like the $set
  • $merge -> the merge command examples are exclusive for merging collections and in this case, I could not find a way to use the Merge method in the API.

Any one can throw light here!??

thanks Paulo Aboim Pinto

1 Answers

I found a way to execute the command using the MongoDb.Driver but I thing there should be a better and fluent way of doing it

var filter = Builders<QueueCollection>.Filter.And 
(
   Builders<QueueCollection>.Filter.Eq(x => x.WorkerName, string.Empty),
   Builders<QueueCollection>.Filter.Eq(x => x.Processed, false)
);

var sortOptions = Builders<QueueCollection>
   .Sort.Ascending("LastTimeChanged");

this.queueCollection.Aggregate()
   .Match(filter)
   .Sort(sortOptions)
   .Limit(1)
   .AppendStage<QueueCollection>("{ $set: { 'WorkerName': 'WORKER_NAME' } }")
   .AppendStage<QueueCollection>("{ $merge: 'Queue' }")
   .ToList();

This works for now, but I would like to want still to know:

  • How do I replace the $set in the Aggregate pipeline
  • How do I write a proper $merge command.

thanks in advance for any answer Paulo Aboim Pinto

Related