简体   繁体   中英

How to include attributes in MongoDB aggregation

I'm trying to include the original attributes in the model along with the count

const tickers = async (ctx) => {
    let data = await ReadSchema.aggregate([
     { "$project": { "tickers.symbol": 1 }},
     { "$unwind": "$tickers" },
     { "$group": { "_id": "$tickers.symbol", "count": { "$sum": 1 }}},
      //  {
      //  "$addFields": {
      //     exchange: "$tickers.exchange",
      //     name: "$tickers.name",
      //     symbol: "$tickers.symbol",
      //   },
      // },
     { $sort: { "count": -1 }},
    ]);

    ctx.body = data;
};

Here is the schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ReadSchema = new Schema(
  {
    tickers: [{ name: 'String', symbol: 'String', exchange: 'String' }],
  },
  { timestamps: true },
);

I'm only getting _id and count in output...I want symbol , name and exchange too.

Quick Fixes,

  • { "$project": { "tickers.symbol": 1 }}, after this stage the pipeline have only symbol field, you can't access other fields (name, exchange) in below stages like group, so just change this stage to
{ "$project": { "tickers": 1 } },
  • You need to pass that fields in $group stage using $frist or either $last operators,
{ 
  "$group": { 
    "_id": "$tickers.symbol", 
    "count": { "$sum": 1 },
    "exchange": { "$first": "$tickers.exchange" },
    "name": { "$first": "$tickers.name" }
  }
}

Your final query would be:

const tickers = async (ctx) => {
    let data = await ReadSchema.aggregate([
        { "$project": { "tickers": 1 } },
        { "$unwind": "$tickers" },
        { 
            "$group": { 
                "_id": "$tickers.symbol", 
                "count": { "$sum": 1 },
                "exchange": { "$first": "$tickers.exchange" },
                "name": { "$first": "$tickers.name" }
            }
        },
        {
            "$project": {
                "_id": 0,
                "symbol": "$_id",
                "exchange": 1,
                "name": 1,
                "count": 1
            }
        },
        { $sort: { "count": -1 } }
    ]);
    ctx.body = data;
};

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