大家好,我需要一些帮助,我想在特定领域进行一些投影,但在投影阶段内,我还想根据某些条件制作一个过滤器并进行排序。 这是聚合
[
{
'$match': {
'_id': ObjectId('659dfebd24358fa4604510bb')
}
}, {
'$project': {
'date': 1,
'serviceScheduleId': 1,
'serviceId': 1,
'branchOfficeId': 1,
'companyId': 1,
'queue': {
'$filter': {
'input': '$queue',
'cond': {
'$and': [
{
'$eq': [
'$$this.queueType', 'online'
]
}, {
'$eq': [
'$$this.checkinTime', None
]
}, {
'$eq': [
'$$this.user.status', 'incall'
]
}
]
}
},
'$sortArray': {
'input': '$queue',
'sortBy': {
'user.ticketInt': -1
}
}
}
}
}, {
'$group': {
'_id': '$_id',
'items': {
'$push': '$queue'
}
}
}, {
'$unwind': {
'path': '$queue'
}
}
]
这是我的 mongodb 游乐场 https://mongoplayground.net/p/WNnSOzQKUJB
当我在 mongodb compas 上执行代码时,它显示一些像这样的错误
由于 :: FieldPath 字段名称可能不以“$”开头而导致 $project :: 无效。考虑使用 $getField 或 $setField。
您不能使用带有前缀:
$
的字段作为字段名称。
方法 1:创建另一个
$set
/ $project
阶段
db.collection.aggregate([
// Match stage,
{
"$project": {
"date": 1,
"serviceScheduleId": 1,
"serviceId": 1,
"branchOfficeId": 1,
"companyId": 1,
"queue": {
"$filter": {
"input": "$queue",
"cond": {
"$and": [
{
"$eq": [
"$$this.queueType",
"online"
]
},
{
"$eq": [
"$$this.checkinTime",
null
]
},
{
"$eq": [
"$$this.user.status",
"incall"
]
}
]
}
}
}
}
},
{
$set: {
queue: {
"$sortArray": {
"input": "$queue",
"sortBy": {
"user.ticketInt": -1
}
}
}
}
}
])
方法 2:将
$filter
运算符放置在 input
的 $sortArray
字段中
db.collection.aggregate([
// Match stage,
{
"$project": {
"date": 1,
"serviceScheduleId": 1,
"serviceId": 1,
"branchOfficeId": 1,
"companyId": 1,
"queue": {
"$sortArray": {
"input": {
"$filter": {
"input": "$queue",
"cond": {
"$and": [
{
"$eq": [
"$$this.queueType",
"online"
]
},
{
"$eq": [
"$$this.checkinTime",
null
]
},
{
"$eq": [
"$$this.user.status",
"incall"
]
}
]
}
}
},
"sortBy": {
"user.ticketInt": -1
}
}
}
}
}
])