简体   繁体   中英

How can I filter array of objects into MongoDB Document

I'm using Express as my backend and MongoDB as the data base. My models looks like this:

Pyments:

var pymentSchema = new mongoose.Schema({
  name: {
    type: String,
    enum: [
        "VISA",
        "MASTERCARD",      
        "CASH",     
        ],
    required: [true, "Need a type of pyment"],
    },  
  total: {
    type: Number,
    default:0
    }, 
  });

Bill:

var billingSchema = new mongoose.Schema({  
    pyments: {
        type: [Pyments],
        required: true,
        default:[]
        }});

My stored data looks like this:

"Bill": [
    {
        "_id": "5fe17af4a0f04d088ca24d36",
        "pyments": [
            {
                "total": 1.6,
                "name": "VISA"
            },
            {
                "total": 1.25,
                "name": "CASH"
            }
        ]
    },
    {
        "_id": "5fe8d6ede7adc919d4299d02",
        "pyments": [
            {
                "total": 1.61,
                "name": "VISA"
            },
            {
                "total": 1.00,
                "name": "MASTERCARD"
            },
            
        ]
    },
    {
        "_id": "5fea68a2eb0e382a50dae7a6",
        "pyments": [
            {
                "total": 2.5,
                "name": "VISA"
            },
            {
                "total": 3.38,
                "name": "MASTERCARD"
            }
        ]
    }]

All I want is to get for example the total only in VISA , CASH and MASTERCARD like this: (Object returned)

{        
    "Totals": [
        {
            "total": 5.71,
            "name": "VISA"
        },
        {
            "total": 1.25,
            "name": "CASH"
        },
        {
            "total": 4.38,
            "name": "MASTERCARD"
        }
    ]
}

I really don't have an idea what to do in this case, any help will be appreciated.

You can use aggregation method aggregate() , and below pipeline stages,

  • $unwind deconstruct pyments array
  • $group by pyments.name and get total sum of pyment.total using $sum
BillSchemaModel.aggregate([
  { $unwind: "$pyments" },
  {
    $group: {
      _id: "$pyments.name",
      total: { $sum: "$pyments.total" }
    }
  }
])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM