Добавить поле в коллекцию с условием в mongodb - PullRequest
0 голосов
/ 11 февраля 2020

Я хочу добавить новое логическое поле в коллекцию с информацией другого поля.

Мой пример данных:

{ 
    "_id" : ObjectId("50abae61edecb53c740022eb"), 
    "pull_request" : {
        "diff_url" : null, 
        "patch_url" : null, 
        "html_url" : null
    }
}
{ 
    "_id" : ObjectId("50abae61edecb53c740022ec"), 
    "pull_request" : {
        "diff_url" : "https://github.com/joyent/http-parser/pull/106.diff", 
        "patch_url" : "https://github.com/joyent/http-parser/pull/106.patch", 
        "html_url" : "https://github.com/joyent/http-parser/pull/106"
    }, 
} 

Новое поле "hasPullRequest"; если поле pull_request имеет значение null, hasPullRequest: false; в противном случае hasPullRequest: true. Я имею в виду, что ниже;

{ 
    "_id" : ObjectId("50abae61edecb53c740022eb"), 
    "pull_request" : {
        "diff_url" : null, 
        "patch_url" : null, 
        "html_url" : null
    },
    "hasPullRequest" : false
}
{ 
    "_id" : ObjectId("50abae61edecb53c740022ec"), 
    "pull_request" : {
        "diff_url" : "https://github.com/joyent/http-parser/pull/106.diff", 
        "patch_url" : "https://github.com/joyent/http-parser/pull/106.patch", 
        "html_url" : "https://github.com/joyent/http-parser/pull/106"
    }, 
    "hasPullRequest" : true
} 

Я пробовал этот запрос, но он не работал;

db.getCollection('issues').aggregate([
   {
     $addFields: {
       hasPullRequest:  { 
            "$cond": {
            if: { { "$eq": {"$pull_request": null}} ,
            then: false,
            else: true
            } 
      }
   }
])

Как я могу это сделать?

Ответы [ 4 ]

1 голос
/ 12 февраля 2020

Поскольку в некоторых записях нет поля pull_request, я добавил условие или;

    db.getCollection("test").aggregate( [ 
  { 
      $addFields: { 
          hasPullRequest: { 
             $cond: [ 
                 { 
                     $or:
                     [ 
                         { $and: [ 
                            { $eq: [ "$pull_request.diff_url", null ] },
                            { $eq: [ "$pull_request.patch_url", null ] },
                            { $eq: [ "$pull_request.html_url", null ] },
                                 ]
                         },
                         {  $eq:[{ $ifNull: [ "$pull_request", 0 ] },0]  }
                      ]
                  },
                 false, 
                 true 
             ] 
          } 
      } 
  },
  {
        $out: "Issues2"
  }
]
).pretty()

Это прекрасно сработало для меня.

1 голос
/ 12 февраля 2020

Проблема в условии вашего запроса - { "$eq": {"$pull_request": null}}. Это должно быть одно из следующих значений:

db.test.aggregate( [ 
  { 
      $addFields: { 
          hasPullRequest: { 
             $cond: [ 
                 { $eq: [ "$pull_request", { diff_url: null, patch_url: null, html_url: null } ] }, 
                 false, 
                 true 
             ] 
          } 
      } 
  }
] ).pretty()

db.test.aggregate( [ 
  { 
      $addFields: { 
          hasPullRequest: { 
             $cond: [ 
                 { $and: [ 
                        { $eq: [ "$pull_request.diff_url", null ] },
                        { $eq: [ "$pull_request.patch_url", null ] },
                        { $eq: [ "$pull_request.html_url", null ] }
                 ] },
                 false, 
                 true 
             ] 
          } 
      } 
  }
] ).pretty()



[EDIT ADD]
db.test.aggregate( [ 
  { 
      $facet: {
           pull_req_no: [
               { $match: { pull_request: { $exists: false } } },
               { $addFields: { hasPullRequest: false } }
           ],
           pull_req_yes: [
               { $match: { pull_request: { $exists: true } } },
               { $addFields: { 
                      hasPullRequest: {
                          $cond: [ 
                              { $and: [ 
                                  { $eq: [ "$pull_request.diff_url", null ] },
                                  { $eq: [ "$pull_request.patch_url", null ] },
                                  { $eq: [ "$pull_request.html_url", null ] }
                              ] },
                              false, 
                              true
                          ]
                      }  
               } }
           ]
      }
  },
  {
      $project: { result: { $concatArrays: [ "$pull_req_no", "$pull_req_yes" ] } }
  },
  { 
      $unwind: "$result" 
  },
  { 
      $replaceRoot: { newRoot: "$result" } 
  }
] ).pretty()
0 голосов
/ 11 февраля 2020

Вы можете попробовать это:

db.issues.aggregate([
  {
    $addFields: {
      hasPullRequest: {
        $cond: [
          {
            $or: [
              {
                $eq: [
                  "$pull_request",
                  null
                ]
              },
              {
                $eq: [
                  {
                    $size: {
                      $objectToArray: "$pull_request"
                    }
                  },
                  0
                ]
              },
              {
                $ne: [
                  {
                    $size: {
                      $objectToArray: "$pull_request"
                    }
                  },
                  {
                    $size: {
                      $filter: {
                        input: {
                          $objectToArray: "$pull_request"
                        },
                        cond: {
                          $ne: [
                            "$$this.v",
                            null
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            ]
          },
          false,
          true
        ]
      }
    }
  }
])

MongoPlayground

0 голосов
/ 11 февраля 2020

вы можете попробовать использовать $ ifNull , например:

db.getCollection('nameColl').aggregate([
   {
    $addFields: 
        {
            newField: 
                {
                    $cond: {if:{$eq:[{ $ifNull: [ "$field", 0 ] },0] }   , 
                    then: false, 
                    else: true }
                }
        }       
}        
])
...