我正在为 mongodb 中的基本查找而苦苦挣扎。尝试多种组合后,我无法弄清楚出了什么问题。我看到有很多关于 SO 解决它的问题,但在尝试所有答案后没有任何效果。
这是我的用户集合
这是我的物品收藏
每个项目都有一个所有者,它映射到用户集合中用户的 _id。对于我的查询,我试图通过相应的用户获取项目。这是查询
db.items.aggregate([
{
"$lookup" : {
localField : "owner",
from : "users",
foreignField : "_id",
as : "users"
}
}
])
它返回这个 -
我尝试了不同的变化 - 例如
db.items.aggregate([
{
"$lookup" : {
localField : "owner.str",
from : "users",
foreignField : "_id.str",
as : "users"
}
}
])
这导致用户数组填充不正确(所有用户!)。
我究竟做错了什么?
编辑
这是项目集合
{
"_id": {
"$oid": "5b268395c176db1548bd92c2"
},
"title": "Item #1",
"description": "Item 1 Description",
"categories": [
{
"$ref": "categories",
"$id": {
"$oid": "5b268248c176db1548bd92af"
}
}
],
"status": "borrowed",
"image": "http://cdn.site.com/testimage.png",
"borrower": "5b2684a0c176db1548bd92d5",
"owner": {
"$ref": "users",
"$id": {
"$oid": "5aecc8012d3d947ba130800d"
}
}
}
{
"_id": {
"$oid": "5b2c2c4d3c70af2da07d1266"
},
"title": "Item 2",
"description": "Item 2 Description",
"categories": [
{
"$ref": "categories",
"$id": {
"$oid": "5b268248c176db1548bd92af"
}
}
],
"status": "Available",
"image": "http://cdn.site.com/testimage1.png",
"borrower": null,
"owner": {
"$ref": "users",
"$id": {
"$oid": "5b2684a0c176db1548bd92d5"
}
}
}
这是用户集合:
{
"_id": {
"$oid": "5aecc8012d3d947ba130800d"
},
"email": "[email protected]",
"registeredOn": "20/10/2018 12:12:29 AM",
"avatarURL": "http://gravtar.com/12334",
"friends": []
}
{
"_id": {
"$oid": "5b2684a0c176db1548bd92d5"
},
"email": "[email protected]",
"registeredOn": "20/10/2018 12:12:29 AM",
"avatarURL": "http://gravtar.com/12334",
"friends": [],
"wishlist": [
{
"$ref": "items",
"$id": {
"$oid": "5b2831543c70af2da07d11da"
}
}
]
}
在localField
和foreignField
应该是相同的数据类型。你分别是DBRef
和ObjectId
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句