首页 > 解决方案 > 难以理解项目如何与 mongoDB 聚合框架一起工作

问题描述

我使用了 2 个管道,我希望它们在使用 count/itcount() 时返回相同数量的结果。

我知道的第一个管道是正确的:count is 1597

var pipeline = [
{ $match: { 
    "writers" : { $elemMatch: { $exists: true } }, 
    "cast" : { $elemMatch: { $exists: true } },
    "directors" : { $elemMatch: { $exists: true } } 
    }
},
{ $project : {
    "writers" : {
        $map : { 
            input: "$writers",
            as: "writer",
            in: { 
                $arrayElemAt: [
                    { $split: [ "$$writer", " (" ] },
                    0
                ]}
        }
    },
    "cast" : 1,
    "directors" : 1 
    }
},
{ $project: 
    { "laborOfLove": { $gt: [ { $size: { $setIntersection: ["$writers", "$cast", "$directors"] } }, 0 ] } }
},
{ $match : { "laborOfLove" : true } }];

我编写的第二个管道并返回更少的文档:计数为 1293

 var pipeline = [
{ $match: {
        "writers" : { $elemMatch: { $exists: true } }, 
        "cast" : { $elemMatch: { $exists: true } },
        "directors" : { $elemMatch: { $exists: true } } 
        }
    },
  {
    $project: {
        _id: 0,
        writers: {
          $map: {
            input: "$writers",
            as: "writer",
            in: {
              $arrayElemAt: [
                {
                  $split: [ "$$writer", " (" ]
                },
                0
              ]
            }
          }
        },
        directors: 1,
        cast: 1,
        "laborOfLove": { $gt: [ { $size: { $setIntersection: ["$writers", "$cast", "$directors"] } }, 0 ] } 
    }},
    { $match : { "laborOfLove" : true } }
]

为什么我得到不同数量的结果?

我正在做 mongoDB 大学聚合框架课程,这是数据的链接:

mongo "mongodb://cluster0-shard-00-00-jxeqq.mongodb.net:27017,cluster0-shard-00-01-jxeqq.mongodb.net:27017,cluster0-shard-00-02-jxeqq.mongodb。 net:27017/aggregations?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl -u m121 -p aggregations --norc

and after creating the pipeline we can run the query like this:

db.movies.aggregation(pipeline).itcount()

标签: mongodbaggregation-framework

解决方案


I understand the situation, I need to put the laborOfLove in a new stage because in the logical order if it's in the same stage I'll go iterate over the writes in the wrong format and that's the reason I get a lower number.


推荐阅读