首页 > 解决方案 > 在单个字段上返回带有条件的查找结果

问题描述

我有以下架构:

  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所有图像都为“假”(换句话说,用户没有isFlaged设置为真的图像)

就像上面数据的结果应该返回 users with userIds Id3 and Id4,因为他们所有的图像都isFlaged为假,没有一个为真

我尝试了以下方法

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 非常了解。

标签: mongodbmongodb-queryaggregation-frameworklookup

解决方案


您只需要纠正$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
    }
  }
])

操场


推荐阅读