MongoDB聚合查找删除数组
我目前正在使用 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 } }
],
});
数据返回一个像这样的对象数组
{
"_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
}
现在的问题是,我使用 lookup()
方法返回的作者对象作为大批。如何让它不以数组形式返回?
I am currently using an aggregate lookup method from mongoose and it works:
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 } }
],
});
The data returns an array of object like this
{
"_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
}
Now the problem is, the author object that I used the lookup()
method on returns as an array. How do I make it not return as an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在查找后使用 $unwind ,如下所示:
You can use $unwind after lookup like this: