Return 具有单个字段条件的查找结果

Return lookup results with condition on single field

我有以下架构:

  User Schema: 
   { userId:"Id1",name:"abc"}, { userId:"Id2",name:"efg"}, { userId:"Id3",name:"lmn"}, { userId:"Id4",name:"xyz"}

  Image Schema:
   { userId:"Id1",imageUrl:"url1",isFlaged:true},{ userId:"Id1",imageUrl:"url2",isFlaged:false},{ userId:"Id1",imageUrl:"url3",isFlaged:false},
   { userId:"Id2",imageUrl:"url4",isFlaged:true},{ userId:"Id2",imageUrl:"url5",isFlaged:false},
   { userId:"Id3",imageUrl:"url6",isFlaged:false},{ userId:"Id3",imageUrl:"url7",isFlaged:false},
   { userId:"Id4",imageUrl:"url8",isFlaged:false},{ userId:"Id4",imageUrl:"url9",isFlaged:false},

我想获取所有没有标记图像的用户 ID,即 isFlaged 是 'false' 的所有图像(换句话说,用户没有图像 isFlaged 设为真)

像上面数据的结果应该 return users with userIds Id3 and Id4 因为他们所有的图像都有 isFlaged 为假,none 为真

我尝试过以下方法

db.users.aggregate([
        {
          $lookup: {
            from: 'images',
            let: {userID: '$userId'},
            pipeline: [
              {
                $match: {
                  $expr: {
                    $and: [{$eq: ['$userId','$$userID']},
                    // tried this too {$ne: ['$isFlaged',false]}],
                  },
                },
              },
              {
                $project: {
                  _id: 0,
                  imageUrl: 1,
                  isFlaged:1,
                }
              },
            ],
            as: 'image',
          },
        },
        {
            $match:{
              '$image.isFlaged':{
                 $nin:[true]  // or using {$not:{$all:[false]}}
               } 
            }
        },
        {
          $limit: 10
        },
        {
          $project: {
            userId: 1,
            image: '$image'
          },
        }
      ]);

我不擅长聚合。我只是尝试尝试查询,但似乎没有任何效果。所以谁能告诉我你是怎么做到的?或者任何有用的链接也会有帮助。我不确定要使用什么查询或方法,因为我对 monogodb 了解很多。

您只需要更正$match舞台条件

  • "image.isFlaged" 不应该为真并且 image 不等于空
db.users.aggregate([
  {
    $lookup: {
      from: "images",
      let: { userId: "$userId" },
      pipeline: [
        {
          $match: {
            $expr: { $eq: ["$$userId", "$userId"] } }
          }
        },
        { $project: { _id: 0, imageUrl: 1, isFlaged: 1 } }
      ],
      as: "image"
    }
  },
  { $match: { image: { $ne: [] }, "image.isFlaged": { $ne: true } } },
  { $limit: 10 },
  {
    $project: {
      userId: 1,
      image: 1
    }
  }
])

Playground