mongodb - MongoError: $match with $text 只允许作为第一个管道阶段
问题描述
我有 MongoDb 与搜索文本聚合。但是 mongoDb throw Execption, idk 也许我的聚合是错误的?或者我不能使用 $match 超过 1 次?抱歉,我是 MongoDB 新手
const current_date = new Date()
var two_days_ago = current_date
two_days_ago.setDate(current_date.getDate() - 2)
return Post.aggregate([
{ $match: { editorChoice: false }},
{ $match: { $text: { $search: category } } },
{ $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
{ $sort: {'likeCount': -1} },
{ $limit: 80 },
{ $lookup: {
from: 'likes',
let: { postUid: '$_id' },
pipeline: [ {
$match: {
$expr: {
$and: [
{ $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
{ $eq: ['$post_id', '$$postUid'] } ]
}
}
} ],
as: 'likes' } },
{ $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
{ $lookup: {
from: 'locations',
localField: 'location',
foreignField: '_id',
as: 'location' } },
{ $unwind: {
path: '$location',
preserveNullAndEmptyArrays: true }},
{ $lookup: {
from: 'sticker_images',
localField: 'sticker',
foreignField: '_id',
as: 'sticker' } },
{ $unwind: {
path: '$sticker',
preserveNullAndEmptyArrays: true }},
{ $lookup: {
from: 'prangko_images',
localField: 'prangko',
foreignField: '_id',
as: 'prangko' } },
{ $unwind: {
path: '$prangko',
preserveNullAndEmptyArrays: true }},
{ $project: aggregate_project }
]).exec()
但我有类似的文本搜索聚合但没有这个
{ $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
它是我的 $match 错误还是关于 Date 变量的东西?
解决方案
试试这样
return Post.aggregate([
{ $match: { $text: { $search: category } } },
{ $match: { editorChoice: false }},
{ $match: { $expr: { $and: [{ $gte: ["$createdAt", two_days_ago ] }, { $lte: ["$createdAt", current_date ] }] } } },
{ $sort: {'likeCount': -1} },
{ $limit: 80 },
{ $lookup: {
from: 'likes',
let: { postUid: '$_id' },
pipeline: [ {
$match: {
$expr: {
$and: [
{ $eq: ['$user_id', mongose.Types.ObjectId(user_id)] },
{ $eq: ['$post_id', '$$postUid'] } ]
}
}
} ],
as: 'likes' } },
{ $addFields: { isLike: { $eq: ['$likeCount', 1] } } },
{ $lookup: {
from: 'locations',
localField: 'location',
foreignField: '_id',
as: 'location' } },
{ $unwind: {
path: '$location',
preserveNullAndEmptyArrays: true }},
{ $lookup: {
from: 'sticker_images',
localField: 'sticker',
foreignField: '_id',
as: 'sticker' } },
{ $unwind: {
path: '$sticker',
preserveNullAndEmptyArrays: true }},
{ $lookup: {
from: 'prangko_images',
localField: 'prangko',
foreignField: '_id',
as: 'prangko' } },
{ $unwind: {
path: '$prangko',
preserveNullAndEmptyArrays: true }},
{ $project: aggregate_project }
]).exec()
推荐阅读
- python - 如何在python中打印二维数组
- javascript - 从弹出窗口重定向时恢复窗口大小
- linux - 错误的性能回溯
- reactjs - 在 React 中,如何在运行时而不是在实例化时将数据传递给孩子
- java - 尝试在另一个方法中实现 2 个方法时出错 - java
- javascript - 可以用节点进行弹性搜索,只更新某个字段而不重写吗?
- graphviz - 如何创建一个所有断开组件垂直对齐的图形?
- reactjs - 在 React 的自动完成字段中为键入的字母添加标签
- reactjs - 如何修复'TypeError:null不是对象(评估'data [index]')
- java - Java查找给定日期的工作日