簡體   English   中英

MongoDB 中的項目字段,我不知道中間字段名稱

[英]project field in MongoDB with I don't know intermediates field name

  1. 像 JSON 一樣的文檔
    {
      "matchs":{
        "aus":{
          "won":[2019, 2020],
          "lose":[2018, 2017]
        },
        "pak":{
          "won":[2002, 2003, 2004],
          "lose":[]
        }
      }
     }
  1. 我想在每個國家選擇獲勝的比賽

  2. 像 $project 或 $match 條件中的 "match.*.won"

  3. 喜歡

     db.collection.aggregate([{$match:{"matchs":{"*.won":{$exists:true}}}}])
  4. 輸出如:

    [{"matchs":{"aus":{"won":[2019, 2020]},"pak":{"won":[2002, 2003, 2004]}}]

而不是過濾won ,刪除lose會更快。 會是這個:

db.collection.aggregate([
   { $set: { matchs: { $objectToArray: "$matchs" } } },
   { $unset: "matchs.v.lose" },
   { $set: { matchs: { $arrayToObject: "$matchs" } } }
]) 

或者,如果您更喜歡$set

db.collection.aggregate([
   { $set: { matchs: { $objectToArray: "$matchs" } } },
   {
     $set: {
       "matchs": {
         $map: {
           input: "$matchs",
           in: { k: "$$this.k", v: {won: "$$this.v.won" } }
         }
       }
     }
  },
  { $set: { matchs: { $arrayToObject: "$matchs" } } }
]) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM