我已经在互联网和StackOverflow上搜索了,但是我找不到答案甚至问题。
我有两个集合,一个是报告
,另一个是用户
。 我希望我的查询返回所有报告,并指示指定的用户是否将该报告添加到其数组中作为收藏夹。
报告集合
{ _id: 1, name:"Report One"}
{ _id: 2, name:"Report Two"}
{ _id: 3, name:"Report Three"}
用户集合
{_id: 1, name:"Mike", favorites: [1,3]}
{_id: 2, name:"Tim", favorites: [2,3]}
当users.name="Mike"时期望的结果
{ _id: 1, name:"Report One", favorite: true}
{ _id: 2, name:"Report Two", favorite: false}
{ _id: 3, name:"Report Three", favorite: true}
我能找到的所有答案都在本地字段(
reports
)上使用$unwind,但在这种情况下,本地字段不是一个数组。外部字段是数组。我该如何展开外部字段?是否有更好的方法来处理这个问题?
我在网上看到有人建议创建另一个集合
favorites
,其中包含:{ _id: 1, userId: 1, reportId: 1 }
{ _id: 2, userId: 1, reportId: 3 }
{ _id: 3, userId: 2, reportId: 2 }
{ _id: 4, userId: 2, reportId: 3 }
这种方法似乎是不必要的。按照逻辑应该可以很简单地连接到外部数组中的ID,对吧?
name
和id
,会怎么样? - Abe Caymo