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

How to make mongodb display a calculation used as a sort criterion

如何让第三行的排序计算也显示出来?

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" }
    }}
]);

希望这对你有用

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" }
    }}
]);