MongoDB聚合查找移除数组
MongoDB aggregate Lookup remove array
我目前正在使用 mongoose 的聚合查找方法,它有效:
const data = await this.messageModel.aggregate([
{
$match: { channel_id: channel_id },
},
{
$limit: limit ? limit : 1000,
},
]).lookup({
from: 'users',
localField: 'author',
foreignField: 'id',
as: 'author',
pipeline: [
{ $project: { _id: 0, password: 0, email: 0, __v: 0 } }
],
});
数据return是一个像这样的对象数组
{
"_id": "622861fe264eaed05a32bb2d",
"channel_id": "5850473746686541647",
"author": [
{
"username": "UnusualAbsurd",
"status": "Working...",
"createdAt": "2022-03-08T14:02:53.728Z",
"id": "1"
}
],
"id": "5850638795510120271",
"createdAt": "2022-03-09T08:14:54.228Z",
"attachments": [],
"content": "zazaza",
"__v": 0
}
现在的问题是,我在returns 上使用lookup()
方法的作者对象作为一个数组。如何使它不是 return 作为数组?
您可以像这样查找后使用 $unwind:
{$unwind: '$author'}
我目前正在使用 mongoose 的聚合查找方法,它有效:
const data = await this.messageModel.aggregate([
{
$match: { channel_id: channel_id },
},
{
$limit: limit ? limit : 1000,
},
]).lookup({
from: 'users',
localField: 'author',
foreignField: 'id',
as: 'author',
pipeline: [
{ $project: { _id: 0, password: 0, email: 0, __v: 0 } }
],
});
数据return是一个像这样的对象数组
{
"_id": "622861fe264eaed05a32bb2d",
"channel_id": "5850473746686541647",
"author": [
{
"username": "UnusualAbsurd",
"status": "Working...",
"createdAt": "2022-03-08T14:02:53.728Z",
"id": "1"
}
],
"id": "5850638795510120271",
"createdAt": "2022-03-09T08:14:54.228Z",
"attachments": [],
"content": "zazaza",
"__v": 0
}
现在的问题是,我在returns 上使用lookup()
方法的作者对象作为一个数组。如何使它不是 return 作为数组?
您可以像这样查找后使用 $unwind:
{$unwind: '$author'}