我正在 Go 1.9.2
中使用 mongoDB 3.4
开发一个 api 我正在使用 mgo
作为驱动程序。
在将请求及其结果插入具有两个集合的同一个数据库后,我必须做一个端点来获取请求的结果。
有两个集合:
第一个集合:请求
第二个集合:结果
requests
集合的格式为
{ "_id":ObjectId("5afc034f53c9a77a598c8345")
" time ":"2018-05-16 10:08:35.024352907 +0000 UTC m=+23.407317980"
"param_request":[name:"mike",age:"30",job:"Doctor"]
}
results
集合的格式 id_request
字段是请求文档的 _id
字段(作为 SQL 中的外键哲学)
{"_id":ObjectId("5afc035b53c9a77a598c8346")
"id_request":ObjectId("5afc034f53c9a77a598c8345")
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"Tokyo"}
{"_id":ObjectId("5afc035b53c9a77a598c8347")
"id_request":ObjectId("5afc034f53c9a77a598c8345")
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"London"}
{"_id":ObjectId("5afc035b53c9a77a598c8349")
"id_request":ObjectId("5afc034f53c9a77a598c8345")
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"Berlin"
}
我尝试查询并从文档中找到了查找 $lookup Documentation
想要的结果:
{
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"Berlin"
}
{
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"London"
}
{
"name":"Mike"
"age":"30"
"job":"Doctor"
"city":"Tokyo"
}
这是我做的:
db.results.aggregate([
{$lookup: {from:requests, localField: "id_request",foreignField:"_id",as:”results”}},
{$match:
{
"id_request": ObjectId("5afc034f53c9a77a598c8345") }}]);
这里是获取错误:
2018-05-16T11:31:51.261+0000 E QUERY [thread1] SyntaxError: missing } after property list @(shell):1:131
以下是我将 SQL 哲学作为查询所获得的:
select results .* from results join requests on
(results.request_id=requests._id
and
request_id='ObjectId("5afc034f53c9a77a598c8345")');
最佳答案
您问题中的查询有多个问题,可能会导致解析错误。查找阶段的 from
属性必须是一个字符串。此外,您用于 as
属性的引号字符 (”
) 不是有效的字符串定界符。
尝试将 from: requests
替换为 from: "requests"
并将 ”
字符替换为单引号或双引号。
db.results.aggregate([
{ $lookup: { from: "requests", localField: "id_request", foreignField: "_id", as: "results" } },
{ $match: { "id_request": ObjectId("5afc034f53c9a77a598c8345") } }
]);
关于mongodb - 在 ObjectId 字段上的两个集合之间进行 $lookup 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368827/