【问题标题】:Pymongo: Aggregate all documents that not have one field and have another - group byPymongo:聚合所有没有一个字段但有另一个字段的文档 - 分组
【发布时间】:2020-03-06 05:10:32
【问题描述】:

我正在尝试从我的集合中获取一组文档,条件如下:

  • 字段:img_status 不存在
  • 字段:图片应该存在

然后,将这些文档(唯一/不同)按一个字段分组。 当我在 MongoDB 中执行查询时,它似乎返回了正确的值:

db.getCollection('products').aggregate([
{ $match: { images: { $exists: true, $ne: null } } },
{ $match: { img_status: { $exists: false } } },
{ $group : { _id:"$vendor_link", "uuid" : {$first: "$uuid"}, "images": { $first: "$images"} } }
])

但在 PyMongo 中,我总是得到相反的结果:img_status exist = true:

pipeline = [
    {
        "$match": 
        {   
            "images" : 
            { "$ne" : "null", "$exists": "true", } 
        }
    },
    {
        "$match": 
        {   
            "img_status": 
            {"$exists": "false"}
        }
    },
    {
        "$group":
        {
            "_id"       : "$vendor_link",
            "images"    : {"$first": "$images"},
            "uuid"      : {"$first": "$uuid"},
            "source"    : {"$first": "$source"}
        }},
]
pprint(list(self.collection.aggregate(pipeline)))

我做错了什么?

【问题讨论】:

    标签: mongodb aggregation-framework pymongo


    【解决方案1】:

    这应该可以解决问题。您正在传递字符串值而不是 None 和布尔值 TrueFalse

    pipeline = [
        {
            "$match": {   
                "images" : {
                    "$ne" : None,
                    "$exists": True,
                } 
            }
        },
        {
            "$match": {
                "img_status": {
                    "$exists": False,
                }
            }
        },
        {
            "$group":{
                "_id"       : "$vendor_link",
                "images"    : {"$first": "$images"},
                "uuid"      : {"$first": "$uuid"},
                "source"    : {"$first": "$source"}
            }
        },
    ]
    pprint(list(self.collection.aggregate(pipeline)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多