MongoDB - 如何根据字段布尔值从查找查询中排除记录?
MongoDB - How to exclude a record from a lookup query based on a field boolean value?
我正在执行查找查询,但想排除查找中的布尔字段值 table 为假的记录,这可能吗?这是我当前的查询:
const pipeline = [
{
'$lookup': {
'from': 'photos',
'localField': '_id',
'foreignField': 'postId',
'as': 'photoData'
}
}, {
'$project': {
'createdAt': 1,
...
'photoData': {
'$cond': {
'if': {
'$eq': [
false, '$photoData.published'
]
},
'then': '$$REMOVE',
'else': '$photoData'
}
}
}
}
]
这是照片集
{
id:'1234',
url:'some.url.com',
published:true
},
{
id:'4567',
url:'some.otherurl.com',
published:false
},
我想从照片集 (photoData) 查找中排除 'published' 设置为 false 的任何记录。我认为使用 'project' 是执行此操作的正确方法,但我不确定,而且我似乎找不到正确的 syntax/logic.
$lookup
returns 一个数组,所以 '$photoData.published' 也将是一个数组,因此永远不会匹配 false。
您可以使用 $filter 从数组中删除未发布的图像,例如:
{$filter: {
input: "$photoData",
as: "photo",
cond: {$ne:["$$photo.published",false]}
}}
``
您可以将 $lookup
与管道一起使用,以执行带有子查询的集合之间的连接:
- 加入
posts
(id) 和 photo
(postId)。
- 仅与
published: true
匹配。
db.posts.aggregate([
{
"$lookup": {
"from": "photos",
let: {
postId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$postId",
"$$postId"
]
},
{
$eq: [
true,
"$published"
]
}
]
}
}
},
],
"as": "photoData"
}
},
{
"$project": {
"createdAt": 1,
"photoData": 1
}
}
])
我正在执行查找查询,但想排除查找中的布尔字段值 table 为假的记录,这可能吗?这是我当前的查询:
const pipeline = [
{
'$lookup': {
'from': 'photos',
'localField': '_id',
'foreignField': 'postId',
'as': 'photoData'
}
}, {
'$project': {
'createdAt': 1,
...
'photoData': {
'$cond': {
'if': {
'$eq': [
false, '$photoData.published'
]
},
'then': '$$REMOVE',
'else': '$photoData'
}
}
}
}
]
这是照片集
{
id:'1234',
url:'some.url.com',
published:true
},
{
id:'4567',
url:'some.otherurl.com',
published:false
},
我想从照片集 (photoData) 查找中排除 'published' 设置为 false 的任何记录。我认为使用 'project' 是执行此操作的正确方法,但我不确定,而且我似乎找不到正确的 syntax/logic.
$lookup
returns 一个数组,所以 '$photoData.published' 也将是一个数组,因此永远不会匹配 false。
您可以使用 $filter 从数组中删除未发布的图像,例如:
{$filter: {
input: "$photoData",
as: "photo",
cond: {$ne:["$$photo.published",false]}
}}
``
您可以将 $lookup
与管道一起使用,以执行带有子查询的集合之间的连接:
- 加入
posts
(id) 和photo
(postId)。 - 仅与
published: true
匹配。
db.posts.aggregate([
{
"$lookup": {
"from": "photos",
let: {
postId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$postId",
"$$postId"
]
},
{
$eq: [
true,
"$published"
]
}
]
}
}
},
],
"as": "photoData"
}
},
{
"$project": {
"createdAt": 1,
"photoData": 1
}
}
])