如何根据猫鼬中另一个文档的存在来获取文档?
How to fetch doc on basis of the existence of another document in mongoose?
我有一个名为 post 的集合,我有一个文档及其复制文档,但在复制文档中我们有一个字段不同,一些文档没有复制文档,这种情况取决于数组文档的字段,如果该字段具有用户的 userId,则复制的文档将存在,否则将不存在。
所以我想要的是,如果文档数组具有该 ID,则获取复制的 post,如果没有,则获取原始的 post
我进行了查询但显示错误 我在 $cond 中使用 $exist ?
Post.aggregate([
{
$match: {
socomo_visibility: socomoId
}
},
{
$project: {
"post_stream_type": {
$cond: {
if: {
'following_users_list': {
$exist: [userId]
}
},
then: constants.POST_STREAM_TYPE.FOLLOW.value,
else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value
}
}
}
}
]
您可以通过以下方式检查您的数组是否在 boolean-expression 中具有某些值:
- 使用$setIntersection对数组和值进行交集。
- 使用 $size 检查交集数组的大小。
- 如果大小大于 0,则数组中存在值。 $gt 将执行此检查。
试试下面的代码:
Post.aggregate([
{
$project: {
"post_stream_type": {
$cond: {
if: {$gt: [{$size: {$setIntersection: ["$following_users_list", [userId]] } }, 0] },
then: constants.POST_STREAM_TYPE.FOLLOW.value,
else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value
}
}
}
}
])
好吧,我终于在不使用聚合的情况下完成了这项工作。
我对查询的回答是
Post.find({
$or: [{
socomo_visibility: {
$elemMatch: {
$eq: socomoId
}
},
post_stream_type: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value,
following_users_list: {
$exists: true,
$nin: [userId]
}
},
{
socomo_visibility: {
$elemMatch: {
$eq: socomoId
}
},
post_stream_type: constants.POST_STREAM_TYPE.FOLLOW.value,
following_users_list: {
$elemMatch: {
$eq: userId
}
}
}]
})
我有一个名为 post 的集合,我有一个文档及其复制文档,但在复制文档中我们有一个字段不同,一些文档没有复制文档,这种情况取决于数组文档的字段,如果该字段具有用户的 userId,则复制的文档将存在,否则将不存在。
所以我想要的是,如果文档数组具有该 ID,则获取复制的 post,如果没有,则获取原始的 post
我进行了查询但显示错误 我在 $cond 中使用 $exist ?
Post.aggregate([
{
$match: {
socomo_visibility: socomoId
}
},
{
$project: {
"post_stream_type": {
$cond: {
if: {
'following_users_list': {
$exist: [userId]
}
},
then: constants.POST_STREAM_TYPE.FOLLOW.value,
else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value
}
}
}
}
]
您可以通过以下方式检查您的数组是否在 boolean-expression 中具有某些值:
- 使用$setIntersection对数组和值进行交集。
- 使用 $size 检查交集数组的大小。
- 如果大小大于 0,则数组中存在值。 $gt 将执行此检查。
试试下面的代码:
Post.aggregate([
{
$project: {
"post_stream_type": {
$cond: {
if: {$gt: [{$size: {$setIntersection: ["$following_users_list", [userId]] } }, 0] },
then: constants.POST_STREAM_TYPE.FOLLOW.value,
else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value
}
}
}
}
])
好吧,我终于在不使用聚合的情况下完成了这项工作。 我对查询的回答是
Post.find({
$or: [{
socomo_visibility: {
$elemMatch: {
$eq: socomoId
}
},
post_stream_type: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value,
following_users_list: {
$exists: true,
$nin: [userId]
}
},
{
socomo_visibility: {
$elemMatch: {
$eq: socomoId
}
},
post_stream_type: constants.POST_STREAM_TYPE.FOLLOW.value,
following_users_list: {
$elemMatch: {
$eq: userId
}
}
}]
})