如何使mongodb显示用作排序标准的计算

时间:2019-03-01 01:57:47

标签: mongodb sorting aggregation

如何显示用于第三行排序的计算?

db.stocks.aggregate([
  {$unwind: '$tickers'},
  {"$sort": {"_id": 1, "1 - (tickers.open/tickers.close)": -1}},
  {"$group": {
    "_id": "$_id",
    "ticker": { "$first": "$tickers.ticker"},
    "open": { "$first": "$tickers.open" },
    "close": { "$first": "$tickers.close" }
    }}
]);

1 个答案:

答案 0 :(得分:0)

希望这对您有用

db.stocks.aggregate([
  {$unwind: '$tickers'},
  {$addFields: {"tickers.calc": {$subtract: [1,{$divide: ["$tickers.open","$tickers.close"]}] } }},
  {"$sort": {"_id": 1, "tickers.calc": -1}},
  {"$group": {
    "_id": "$_id",
    "ticker": { "$first": "$tickers.ticker"},
    "open": { "$first": "$tickers.open" },
    "close": { "$first": "$tickers.close" },
    "calc": { "$first": "$tickers.calc" }
    }}
]);