难以理解项目如何与mongoDB聚合框架一起使用

问题描述 投票:0回答:1

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

我知道正确的第一个管道是:count是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 } }];

我编写并返回较少文档的第二个管道:count是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聚合--norc

并且在创建管道之后,我们可以像这样运行查询:

db.movies.aggregation(pipeline).itcount()
mongodb aggregation-framework
1个回答
0
投票

我了解这种情况,我需要将labourOfLove放到一个新的阶段,因为如果逻辑上处于同一阶段,那么我将按照逻辑顺序对错误格式的写入进行迭代,这就是我得到较低数字的原因。

© www.soinside.com 2019 - 2024. All rights reserved.