如何在mongodb中查询文档并获取键值?

kpbpu008  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(229)

我想从resultInDB中查询所有文档,并以expectedResult片段中给出的方式获取它们。

resultInDB:
 [
   {
     _id:1,
     owners: [
               "johnDoe",
                "michael"
             ],
     stakeholders: [
                    "johnDoe",
                    "david"
                   ]
   },
   {
     _id:2,
     owners: [
                "michael"
             ],
     stakeholders: [
                    "michael",
                    "david"
                   ]
   }
 ]

预期结果:

{
   "johnDoe" :{_id:[1]},
   "michael" :{_id:[1,2]}
   "david" :{_id:[1,2]}  
 }

正如你在结果中看到的,我希望它必须是每个用户的键/值,从所有者或利益相关者到每个用户关联的键和id。

but5z9lq

but5z9lq1#

一种选择是:

db.collection.aggregate([
  {$project: {name: {$setUnion: ["$owners", "$stakeholders"]}}},
  {$unwind: "$name"},
  {$group: {_id: "$name", doc: {$push: "$_id"}}},
  {$group: {_id: 0, res: {$push: {k: "$_id", v: {_id: "$doc"}}}}},
  {$replaceRoot: {newRoot: {$arrayToObject: "$res"}}}
])

了解它在playground example上的工作原理

相关问题