mongodb - 在单个字段上返回带有条件的查找结果
问题描述
我有以下架构:
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 非常了解。
解决方案
您只需要纠正$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
}
}
])
推荐阅读
- vue.js - Vue Cypress 和 Gitlab CI/CD
- c++ - Arduino - 在一定时间内运行 if 条件
- angular - Angular 组件属性
- python - 有没有办法按顺序从列表中添加和减去数字?
- r - R -plm - 内部误差和随机效应模型(池化,之间和第一差异工作)
- angular - 使用 Ngx-translate 翻译存储在 Mysql DB 中的数据
- node.js - 如何在 Sails js 水线数据库关系中设置主键
- angular - AOS 库和 Angular,单击导航栏链接时未触发滚动动画以进行同一页面部分导航
- javascript - 在 Canvas Javascript 中绘图
- c# - 无法隐式转换类型'Emgu.CV.Image
' 到 'System.Drawing.Image'