【发布时间】:2021-10-13 04:00:07
【问题描述】:
我有一个返回对象数组的聚合查询。我试图通过在管道末尾添加这个阶段来分割它:
let limit = 5;
let skip = limit * 1;
const page_limit_stage = {
$project: {
profiles: {
$slice: ["$$CURRENT", skip, limit],
},
},
};
但是,我不断收到此错误:
???? ~ 文件:profile.js ~ 第 331 行 ~ err MongoError: 第一个参数 $slice 必须是数组,但类型为:object
知道如何解决这个问题吗?
编辑 2:这是我正在使用的查询:
const filterProfiles = async function filterProfiles() {
const { users_filter_option, profiles_filter_option } =
prepareProfilesFilterSearchOptions();
const profile_stage = {
$lookup: {
from: "profiles",
let: { profile_id: "$profile" },
pipeline: [profiles_filter_option],
as: "profile",
},
};
const profile_populate_options = [
{
$lookup: {
from: "schema_name_1",
localField: "profile.schema_name_1",
foreignField: "_id",
as: "schema_name_1",
},
},
{
$lookup: {
from: "schema_name_2",
localField: "profile.schema_name_2",
foreignField: "_id",
as: "schema_name_2",
},
},
];
const project_stage = {
$project: {
user_id: "$_id",
name: "$name",
surname: "$surname",
country: "$country",
schema_name_2: { $arrayElemAt: ["$schema_name_2", 0] },
schema_name_1: "$schema_name_1",
},
};
let limit = 5;
let skip = limit * 1;
const page_limit_stage = {
$project: {
profiles: {
$slice: ["$CURRENT", skip, limit],
},
},
};
const pipeline = [
users_filter_option,
profile_stage,
...profile_populate_options,
{ $unwind: "$profile" },
project_stage,
page_limit_stage,
];
const users = await User.aggregate(pipeline);
return users;
};
这是没有page_limit_stage的结果:
[
{
_id: "aegaeg",
user_id: "aegaef",
name: "user_name",
surname: "user_surname",
country: "country_name",
schema_name_1: "value",
schema_name_2: "value2",
},
// multiple documents like this
];
【问题讨论】:
-
它说你的输入字段类型是一个对象但它需要一个数组,为什么
$$,只尝试$?你能发布一个示例文档吗? -
@turivishal 我在编辑中添加了信息
标签: mongodb mongoose mongodb-query aggregation-framework