我搜索过互联网和 StackOverflow,但找不到答案,甚至找不到问题。
我有两个收藏,reports
and users
。我希望我的查询返回所有报告,并指示指定用户是否将该报告作为其数组中的最爱。
报告收集
{ _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}
我能找到的所有答案都在本地使用 $unwind (reports
) 字段,但在本例中本地字段不是数组。外场就是数组。
国外的田野如何放松?有一个更好的方法吗?
我在网上看到有人建议再做一个合集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 应该很简单,对吧?