【问题标题】:Difficulties in understanding how project works with mongoDB aggregation framework难以理解项目如何与 mongoDB 聚合框架一起工作
【发布时间】:2020-04-06 22:16:06
【问题描述】:

我使用了 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 } }];

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

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

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

【问题讨论】:

  • count is 1597 - 你有没有试过删除项目的最后一行,看看你能得到多少?
  • 您可以发布任何示例数据吗?很难理解你想要做什么。
  • 我正在上 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
  • 没有最后一个项目&匹配结果是:40834

标签: mongodb aggregation-framework


【解决方案1】:

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

【讨论】:

  • 在第二个查询中,在评估 labourOfLove 字段时,您可以将 $setIntersection 中的“$writers”替换为 $map 代码。
猜你喜欢
  • 1970-01-01
  • 2012-09-24
  • 2012-10-20
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多