Concatenate all sub-items within a JSON object

I have 2 Objects like this :

[
  {
    _id: ObjectId("62990f96345ef9001d9f2dfe"),
    deletedAt: null,
    expiredAt: ISODate("2022-06-05T19:29:26.746Z"),
    dataBarang: [
      {
        vendor: ObjectId("6215dd91139c99003fe4c7cd"),
        currency: ObjectId("61f750b56ea409001e521043"),
        modelId: 14,
        usdConvertion: 1,
        price: 15,
        leadTime: null,
        quantity: 2
      }
    ],
    cartItems: [
      ObjectId("62990f77345ef9001d9f2dfd")
    ],
    reqNo: "f0124ae0-1072-4f18-ab90-a7d2d784e634",
    reqDate: ISODate("2022-06-03T00:00:00.000Z"),
    updatedAt: ISODate("2022-06-02T19:29:30.140Z"),
    createdAt: ISODate("2022-06-02T19:29:26.747Z"),
    __v: 0,
    pickUpDate: ISODate("2022-06-03T00:00:00.000Z"),
    transactionDate: ISODate("2022-06-03T00:00:00.000Z")
  },
  {
    _id: ObjectId("62990fe9345ef9001d9f2e03"),
    deletedAt: null,
    expiredAt: ISODate("2022-06-05T19:30:49.081Z"),
    dataBarang: [
      {
        vendor: ObjectId("6215dd91139c99003fe4de15"),
        currency: ObjectId("61f750b56ea409001e521043"),
        modelId: 14,
        usdConvertion: 1,
        price: 64.82,
        leadTime: 14,
        quantity: 1
      }
    ],
    cartItems: [
      ObjectId("62990fcc345ef9001d9f2e02")
    ],
    reqNo: "c2b378ad-87fd-4db4-96b8-6812cb1f2229",
    reqDate: ISODate("2022-06-03T00:00:00.000Z"),
    updatedAt: ISODate("2022-06-02T19:30:51.269Z"),
    createdAt: ISODate("2022-06-02T19:30:49.082Z"),
    __v: 0,
    pickUpDate: ISODate("2022-06-03T00:00:00.000Z"),
    transactionDate: ISODate("2022-06-03T00:00:00.000Z")
  }
]

And what I want to achieve is, to Sum the price of dataBarang for each Object every transactionDate. Please take note that each Objects able to have multiple dataBarang.

I tried with my latest code but still not showing something :

    this.myDBservices.aggregate([])
          .match({
            transactionDate: {
              $gte: '2023-01-01',
              $lte: '2023-01-20'
            }
          })
          .group({
            _id: { $dateFromParts:{year:{$year:"$transactionDate"}, month:{$month:"$transactionDate"}, day:{$dayOfMonth : "$transactionDate" }} },
            date: { $first: "$transactionDate" },
            total: { $sum: 1 },
            totalPrice : {
              $map: {
                $sum: "$$dataBarang.quantity"
              }
            }
          });

Maybe someone want to help me what should It be? really appreciate for every help. Thank you

Answer №1

There seems to be several issues with your current approach.

  1. The date fields in your schema are likely set as type date, but you are trying to match them with strings in your initial $match, causing no documents to be matched.
  2. dataBarang.quantity is stored as an array, requiring two `$sum operations for accurate summing of the field.
  3. There are various typos and syntax errors present that will require debugging on your end.

Here is a basic demonstration of how you should use $sum on the dataBarang.quantity field:

db.collection.aggregate([
  {
    $match: {
      transactionDate: {
        $gte: ISODate("2021-01-01"),
        $lte: ISODate("2023-01-20")
      }
    }
  },
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: "$transactionDate",
          unit: "day"
        }
      },
      totalPrice: {
        $sum: {
          $sum: "$dataBarang.price"
        }
      }
    }
  }
])

Mongo Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...

The specified property ID is not found in the User type

I recently started using TypeScript and decided to practice by implementing user authentication with Passport.js in a small application. Challenge The issue I'm facing is related to instructing Passport.js to store the id property of the user in the ...

Designing a MongoDB Schema for Instant Messaging Apps

I have a project in mind that I believe would be a perfect fit for MongoDB because of its speed and scalability capabilities. Currently, I am focusing on a module related to real-time chat. If I were to implement this in a traditional RDBMS, I would break ...

Struggling to enter the command `zip` and accurately anticipating when inference fails in overloaded functions involving generics

There are times when I encounter this issue without understanding why the inference fails. Specifically, zip behaves correctly when directly used, but not when used within pipe, leaving me puzzled. declare const zip: { <A, B>(input: readonly [re ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

Adjust the size of an Angular component or directive based on the variable being passed in

I'm looking to customize the size of my spinner when loading data. Is it possible to have predefined sizes for the spinner? For example: <spinner small> would create a 50px x 50px spinner <spinner large> would create a 300px x 300p ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Is there a method to incorporate absolute paths in SCSS while working with Vite?

Currently, I am experimenting with React + Vite as webpack seems to be sluggish for me. My goal is to create a project starter, but I am facing difficulties in getting SCSS files to use absolute paths. Despite including vite-tsconfig-paths in my vite.confi ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

The Angular CLI suddenly decided to stop providing me with useful lines (without sourcemaps) in the browser console, but interestingly the terminal continues

I recently noticed a change in my Angular project that is using Angular CLI. Instead of receiving error lines from my code, I am getting errors from compiled files like main.js and vendor.js. The 'normal' error messages in my terminal are pointin ...

React typescript - Error: Type 'boolean' is not compatible with the expected type

Check out this demo This is a simple React application built with Typescript. Currently, I am experimenting with React's Context API. I have set up a context named ThemeContext which holds basic theme styling values to be used across different comp ...

Tips for incorporating the closeAutocomplete function into ng4-geoautocomplete

Hey there! I've incorporated the ng4-autocomplete component into my custom component and now I'm trying to figure out how to detect when the autocomplete dropdown closes. Can you help me out with implementing the "closeAutocomplete" method? Let& ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

Determining changes in an object with Angular 2 and Ionic 2

Q) How can I detect changes in an object with multiple properties bound to form fields without adding blur events to each individual field? I want to avoid cluttering the page with too many event listeners, especially since it's already heavy. For e ...

What is the best way to assign an index signature to a plain object?

Currently, I have this object: const events = { i: 'insert', u: 'update', d: 'delete' }; I am struggling to assign an index signature to the object. When I try the following: export interface EventsSignature { [key: ...

What could be the reason for mongoose.find producing an empty Array?

I've set up an express server and I'm having trouble retrieving tracks from my database. Even though I've created the model to match the attributes in my database, it's still returning an empty array. Any assistance would be greatly app ...

Swap out the selector of an Ionic2 component with its contents

I am utilizing Ionic2 along with TypeScript. Let's assume I desire a custom component to include the content of an ion-menu. <sidemenu></sidemenu> //This sidemenu will contain the ion.menu. <ion-nav id="nav" [root]="rootPage" ...

Only one argument is accepted by the constructor of NGRX data EntityServicesBase

In an attempt to enhance the convenience of my application class, I decided to create a Sub-class EntityServices based on the NGRX/data documentation which can be found here. Despite following the provided example, it appears that it does not function pro ...

The Best Way to Filter Mongo Documents Using Nested Objects

Is there a way to locate a room by its ID and confirm that it includes the current player? Within my mongodb database, I have a collection of rooms that contain players who are users. const RoomSchema = new Schema({ players: [{ type: Schema.Types.Objec ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...