我们尝试使用此查询,返回查找为空
db.getCollection('tests').aggregate([
{$match: {typet:'Req'}},
{$project: {incharge:1}},
{$lookup:{
from: "users",
localField: "incharge", //this is the _id user from tests
foreignField: "_id", //this is the _id from users
as: "user"
}}
])
返回json
[
{
"_id": "57565d2e45bd27b012fc4db9",
"incharge": "549e0bb67371ecc804ad23ef",
"user": []
},
{
"_id": "57565d2045bd27b012fc4cbb",
"incharge": "549e0bb67371ecc804ad21ef",
"user": []
},
{
"_id": "57565d2245bd27b012fc4cc7",
"incharge": "549e0bb67371ecc804ad24ef",
"user": []
}
]
我尝试使用这篇文章,但没有任何事情发生MongoDB aggregation project string to ObjectId并与此MongoDB $lookup with _id as a foreignField in PHP
UPDATE
这是文档“用户”
{
"_id" : ObjectId("549e0bb67371ecc804ad24ef"),
"displayname" : "Jhon S."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad21ef"),
"displayname" : "George F."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad23ef"),
"displayname" : "Franc D."
}
3 回答
我最终找到了解决方案,我的Schema在使用ObjectId的mongoose中出现了问题
我改变了
有了这个
并且正在工作
您的查询查询是完美的,但问题是您将 incharge 作为字符串存储到数据库中,而_id:ObjectId('theID')是一个对象而不仅仅是字符串,您无法将
string
(' ')与object
({}进行比较) . 因此,最好的方法是将 incharge 键存储为对象( mongoose.Schema.ObjectId )而不是架构中的字符串 .您只需使用
"_id.str"
即可完成工作 .])
对我来说很好 .