请求检查所有数组元素

Request to check all array elements

我的 MongoDB 语法有问题。
我有两个文件:
胡同(“树”字段是树的ID):

 {
        "_id": {"$oid": "62572d82cc40164fef7f1a56"},
        "name": "good alley",
        "tree": [
          {"$oid": "626976eb4b93122bc617d701"},
          {"$oid": "626976eb4b93122bc617d702"}
        ]
      },

.......
树:

{
            "_id": {"$oid": "626976eb4b93122bc617d701"},
            "dateInstall": {"$date": "2021-02-27T00:00:00.000Z"},
            "species": [
              {"$oid": "62585a63edfc726a4ff24fb8"}
            ]
          },

.......

我需要写一个查询“去年没有种树的小巷”
我的代码

db.alley.aggregate([
    {
        $lookup: {
            from: "tree",
            localField: "tree",
            foreignField: "_id",
            as: "tree"
        }
    },
    {
        $match: {{$not:{$and:[
                    {"tree.dateInstall": {$gt: new ISODate("2020-12-31")}},
                    {"tree.dateInstall": {$lt: new ISODate("2022-01-01")}}
                    ]
            }}}
    }
]);

你应该先 $unwind 小巷里的树,这样你才能正确地 $lookup 树中的树。在查找中使用 pipeline 仅查询去年种植的树木。最后$group树再次进入小巷,用$match过滤掉那些没有树的小巷

db.getCollection("alley").aggregate([
  {
    $unwind: "$tree",
  },
  {
    $lookup: {
        from: "tree",
        let: { tree: "$tree" },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: [ "$$tree", "$_id" ] },
                  { $gt: [ "$dateInstall", new ISODate("2020-12-31") ] },
                  { $lt: [ "$dateInstall", new ISODate("2022-01-01") ] },
                ]
              }
            }
          }
        ],
        localField: "tree",
        foreignField: "_id",
        as: "tree"
    }
  },
  {
    $group: {
      _id: { id: "$_id", name: "$name" },
      trees: { $addToSet: { $first: "$tree" } }
    }
  },
  {
    $match: {
      trees: { $size: 0 }
    }
  }
])