【发布时间】:2020-05-05 14:57:06
【问题描述】:
我在 MongoDB 中有以下对象,我的后端使用的是 nodeJS。从数据库中检索数据。 "_id": "idq2" 和 "_id": "id1" 都在 API 正文中提供给我们。
questions = [
{
"_id": "idq1"
"questiontext": "some question",
"author": "auth2",
"Answers": []
},
{
"_id": "idq2"
"questiontext": "some question",
"author": "auth1",
"Answers": [
{
"_id": "id1",
"author": "auth1",
"comments" [
{
"author": "auth1",
"comment": "some comments",
"rate": 1,
"_id": "idc1"
}
, {
"comment": "some comments",
"_id": "idc2"
"rate": 3
}
, {
"comment": "some comments",
"_id": "idc3"
"rate": 2
}
, {
"comment": "some comments",
"_id": "idc4",
"rate": 5
}
]
},
{
"_id": "id2",
"author": "auth2",
"comments" []
}
]
}]
假设我有“_id”:“idq2”和“_id”:“id1”,我正在尝试获取下面的对象。
预期结果:
Answer = {
"_id": "id1",
"author": "auth1",
"comments" [
{
"author": "auth1",
"comment": "some comments",
"rate": 1,
"_id": "idc1"
},
{
"comment": "some comments",
"_id": "idc3"
"rate": 2
}
, {
"comment": "some comments",
"_id": "idc2"
"rate": 3
}
]
}
为了让这个问题变得简单:如何获取单个“答案”对象,其中“id1”和前 3 个按速率参数按升序排序的 cmets,该对象应该是单个对象。
【问题讨论】:
-
所以你收集了两个文档
"_id": "idq1"和"_id": "idq2"得到"_id": "id1", "author": "auth1"的过滤器是什么? -
我从 API 正文中获取 id,所以我们可以假设我们有这两个 id
-
所以你的意思是说
"_id": "idq2"& Answers array id ::"_id": "id1"?但是你的问题怎么会说"_id": "idq1"? -
是的,我们有这两个 id,我编辑问题以避免混淆:)
标签: mongodb mongoose mongodb-query aggregation-framework