如何使用mongo聚合在子登记中查找数据?
我想从另一个集合中的子图中$查找
数据。我有调查答案,我想按问题类别的姓名进行分组。
调查文档如下所示:
{
_id: new ObjectId("62555be60401f0a21553da9a"),
name: 'new survey',
questions: [
{
text: 'question 1',
category_id: new ObjectId("62555be60401f0a21553da99"),
options: [Array],
_id: new ObjectId("62555be60401f0a21553da9c"),
},
...
}
类别集合只是名称,_id:
{
_id: new ObjectId("62555be60401r0a27553da99"),
name: "category name"
}
我有这样的答案数据:
[
{
answers: {
k: '62555be60401f0a21553da9c',
v: new ObjectId("62555880da8fb89651f6a292")
},
},
{
answers: {
k: '62555880da8fb89651f6a29b',
v: new ObjectId("62555880da8fb89651f6a29e")
},
}
...
]
k
是一个符合中的
数组。_id
的字符串。 susemy.questions
我想获得这样的数据:
[
{
answers: {
k: 'question 1',
v: new ObjectId("62555880da8fb89651f6a292")
},
category: 'category name'
},
{
answers: {
k: 'question 2',
v: new ObjectId("62555880da8fb89651f6a29e")
},
category: 'other category name'
}
...
]
任何帮助都将不胜感激!
我想我可能可以找出类别部分,但是我无法弄清楚如何使用$ lookup
从子图中获取信息。从文档中,我猜想它可能会在查找中进行一些管道。虽然很困难。
I want to $lookup
data from a subdocument in another collection. I have survey answers, and I want to group them by the question category's name.
The survey documents looks like this:
{
_id: new ObjectId("62555be60401f0a21553da9a"),
name: 'new survey',
questions: [
{
text: 'question 1',
category_id: new ObjectId("62555be60401f0a21553da99"),
options: [Array],
_id: new ObjectId("62555be60401f0a21553da9c"),
},
...
}
Category collection is just name and _id:
{
_id: new ObjectId("62555be60401r0a27553da99"),
name: "category name"
}
I have answer data like this:
[
{
answers: {
k: '62555be60401f0a21553da9c',
v: new ObjectId("62555880da8fb89651f6a292")
},
},
{
answers: {
k: '62555880da8fb89651f6a29b',
v: new ObjectId("62555880da8fb89651f6a29e")
},
}
...
]
k
is a string that matches to the _id
in the survey.questions
array.
I'd like to get the resulting data like this:
[
{
answers: {
k: 'question 1',
v: new ObjectId("62555880da8fb89651f6a292")
},
category: 'category name'
},
{
answers: {
k: 'question 2',
v: new ObjectId("62555880da8fb89651f6a29e")
},
category: 'other category name'
}
...
]
any help would be greatly appreciated!
I think I could probably figure out the category part, but I cannot figure out how to use $lookup
to get info from a subdocument. From the docs I'm guessing its maybe some pipeline within a lookup. Pretty stumped though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行这样的操作,使用管道仅匹配
surveys
具有worded._id
与andy> ansy> ansy.k
值匹配的值。请参阅 Playground
也许可以在
$ lookup 为了简化查询的其余部分
You can do something like this, using a pipeline to match only
surveys
that havequestions._id
that matches theanswer.k
valueAs you can see on the playground
Maybe it is possible to filter the results during the
$lookup
in order to simplify the rest of the query