logo
down
shadow

How to use Addfields in MongoDB C# Aggregation Pipeline


How to use Addfields in MongoDB C# Aggregation Pipeline

By : Sebastian Norris
Date : November 29 2020, 01:01 AM
hope this fix your issue As discussed here Using $addFields in MongoDB Driver for C# you can build the aggregation stage yourself with a BsonDocument.
To use the example from https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/
code :
{
  $addFields: {
    totalHomework: { $sum: "$homework" } ,
    totalQuiz: { $sum: "$quiz" }
  }
}
BsonDocument expression = new BsonDocument(new List<BsonElement>() {
    new BsonElement("totalHomeWork", new BsonDocument(new BsonElement("$sum", "$homework"))),
    new BsonElement("totalQuiz", new BsonDocument(new BsonElement("$sum", "$quiz")))
});
BsonDocument addFieldsStage = new BsonDocument(new BsonElement("$addFields", expression));
IAggregateFluent<BsonDocument> aggregate = col.Aggregate().AppendStage(addFieldsStage);
{
  totalHomework: { $sum: "$homework" } ,
  totalQuiz: { $sum: "$quiz" }
}
IAggregateFluent<BsonDocument> aggregate = col.Aggregate()
    .Match(filterDefintion)
    .AppendStage(addFieldsStage)
    .Project(projectionDefintion);


Share : facebook icon twitter icon
MongoDB Aggregation Pipeline Multiple Groups Complicating Pipeline

MongoDB Aggregation Pipeline Multiple Groups Complicating Pipeline


By : UmAir KhAnn
Date : March 29 2020, 07:55 AM
To fix the issue you can do If I understand the question correctly, this is what you're looking for. The key concept is that you can construct compound _id's from multiple fields.
code :
db.collection.aggregate(
[
    {$match: {cdr3_seq_aa_len: {$gt: 3}}},
    {$group: 
         {
              _id: {donor: "$donor", cdr3_seq_aa: "$cdr3_seq_aa"},
              donor_cdr3_seq_aa_count: {$sum: 1},
              cdr3_seq_aa_len: {$first: "$cdr3_seq_aa_len"}
         }
    },
    {$group:
         {
             _id: {donor: "$_id.donor", len: "$cdr3_seq_aa_len"},
             num_strings_with_this_length: {$sum: 1},
             total_doc_count_by_length:
                  {$sum: "$donor_cdr3_seq_aa_count"}
         }
    }
])
MongoDB $geoNear aggregation pipeline (using query option and using $match pipeline operation) giving different no of re

MongoDB $geoNear aggregation pipeline (using query option and using $match pipeline operation) giving different no of re


By : Arthur Milliken
Date : March 29 2020, 07:55 AM
wish helps you Few assumptions:-
1. Assume there are 300 records that match based on the location.
Using $sum and $avg with $addFields in MongoDB Aggregation

Using $sum and $avg with $addFields in MongoDB Aggregation


By : user1416825
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I realize now that while one can do this, all that's really happening here is that one is getting the average of a sum of one value. Because there's no $grouping going on, just one document, not all, is being read, and the average ($avg) of the $sum of that value from that one document is being outputted. And of course, considering it's only one value, the $avg of the $sum is always going to be the same as the original value itself.
code :
value: 10
averageOfValue: 10
Add field to documents after $sort aggregation pipeline which include its index in sorted list using MongoDb aggregation

Add field to documents after $sort aggregation pipeline which include its index in sorted list using MongoDb aggregation


By : sunrise3333
Date : March 29 2020, 07:55 AM
Any of those help One of the workaround for this situation is to convert your all documents into one single array and hence resolve the index of the document using this array with help of $unwind and finally project the data with fields as required.
code :
db.collection.aggregate([
  { $sort: { points: 1 } },
  {
    $group: {
      _id: 1,
      register: { $push: { _id: "$_id", name: "$name", points: "$points" } }
    }
  },
  { $unwind: { path: "$register", includeArrayIndex: "order" } },
  { $match: { "register.name": "x4" } },
  {
    $project: {
      _id: "$register._id",
      name: "$register.name",
      points: "$register.points",
      order: 1
    }
  }
]);
$addFields in mongoDB aggregation pipeline

$addFields in mongoDB aggregation pipeline


By : mistvan22
Date : March 29 2020, 07:55 AM
it fixes the issue As noted by tom slabbaert, $regexMatch is available only on MongoDB 4.2.x, also, your regex is not valid (should either be Test_ or Test_.*).
However, the syntax you are using will only produce customField: true (or false), not a count. Counts are aggregate functions and therefore need to operate on a group of documents. An aggregation pipeline operates on each single document unless you use a grouping stage like $group, $bucket or $count.
code :
[
  { $match: { 'type': { $regex: /Test_.*/ } } },
  { $count: 'customField' }
]
Related Posts Related Posts :
  • Stop Continuation Task upon exception thrown from parent task
  • Is there a way to make msbuild write error output to stderr?
  • Unit testing: TDD with POCO Objects with navigation properties (relationship fixup)
  • GridSplitter disables my RowDefinition style
  • Memory leak only in Release mode
  • how to read specified string from url
  • how to store html code EMail template in a string variable or textbox c#
  • Set Selected Date to TimePicker wpf (TimePickers inside DataTemplate)
  • How to draw line in Silverlight Specifying Height?
  • Stored procedure executes but does not update data
  • ASP.NET ListBox Trouble
  • Why does C# also not allow empty conditions in while loops?
  • Unable to get a block of code into my regex match groups
  • What is difference between dbcontext.Add and dbcontext.AddObject
  • How do I update the file version number of C# DLL without recompiling?
  • Value for html control always null
  • HttpClient hangs when timeout is setting (Windows Phone)
  • Handle Multiple Form tag in asp.net page?
  • create word document with html content in c#
  • Confusion about Find And Replace
  • Format sms messages in Clickatell
  • Automated Function Overload
  • String to date in MS Access SQL statement gives type mismatch error
  • ShowDialog exiting on certain events
  • Is there a try Convert.ToInt32... avoiding exceptions
  • How to move wpf application into minimize tray at Window Start-up C#?
  • How to change display format of long variable?
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org