我有一个示例 Mongoose 对象,如下所示:
{
_id: 5fa849ad4f6be0382363809c,
ratings: {
ratedPersonId: 7,
rating: 7,
timeSpent: 30,
timestamp: 78,
userThreshold: 5
}
},
它包含一个 _id
和一个评级列表,该列表是具有以下功能的子文档。
我创建了一个像这样的聚合管道:
const ratedUser = await this.ratingModel
.aggregate([
{ $project: { ratings: 1 } },
{ $unwind: '$ratings' },
{
$match: {
$and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 5 } }],
},
},
])
.exec()
这适用于第一个条件 ratings.latedPersonId:userId
我的问题是我的第二个条件是评级应大于或等于同一对象中的 userThreshold
字段。
每当我在查询中输入该内容时,它都不会返回任何内容
$and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 'ratings.threshold'} }],
最佳答案
演示 - https://mongoplayground.net/p/AQMsJGkoFcu
使用$expr比较字段
$expr can build query expressions that compare fields from the same document in a $match stage. If the $match stage is part of a $lookup stage, $expr can compare fields using let variables. See Specify Multiple Join Conditions with $lookup for an example. $expr only uses indexes on the from the collection for equality matches in a $match stage. $expr does not support multikey indexes.
db.collection.aggregate([
{
$project: {
ratings: 1
}
},
{
$unwind: "$ratings"
},
{
$match: {
$and: [
{
"ratings.ratedPersonId": 7
},
{
$expr: {
$gte: [
"$ratings.rating",
"$ratings.userThreshold"
]
}
}
],
},
},
])
关于node.js - Mongoose聚合管道: Comparing to own object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66763493/