Mongodb 3.4版本无法在字符串上联接到ObjectId字段

时间:2019-05-08 03:59:06

标签: mongodb lookup objectid

我们有两个集合,一个是状态集合,另一个是用户集合,我正在尝试对这些集合执行查找查询,但是它不返回任何结果

状态收集记录:

"status" : {
    "status" : "success",
    "start_dt2" : ISODate("2018-07-31T19:00:54.774Z"),
    "start_dt" : "2018-07-31 19:00:54",
    "reason" : "here is my report",
    "approved_by" : "5af203e4a19f2d1d854c2be7",
    "end_dt2" : ISODate("2018-08-02T19:26:05.891Z"),
    "end_dt" : "2018-08-02 19:26:05"
}

用户收集记录如下。

{
  "_id" : ObjectId("5af203e4a19f2d1d854c2be7"),
  "username" : "administrator",
  "status" : 1,
  "failed_login_attempts" : 0,
  "user_password" : "",
  "user_role" : "Administrator",
  "force_change" : 0,
  "full_name" : "Administrator",
  "authentication_type" : "local",
  "email" : "",
  "last_login_dt" : ISODate("2019-05-07T13:30:50.926Z"),
  "contributors" : [],
  "expiration_dt" : null,
  "tags" : [],
  "is_system_administrator" : true,
  "is_shared_asset_manager" : true

}

查询:

db.status.aggregate([
{ "$match": { "type": 'manual_activity' } },
{ "$group": {"_id": "$status", "status": {$push: "$status"}}},
{ "$project": {"status": "$status", _id: 0}},   
{"$lookup": {"from": "users", "localField": "status.approved_by", 
"foreignField": "_id", "as": "username"}},
{ $sort: {count: 1} }
])

我想从用户表中获取用户名,而不是从状态收集中获取ID。

0 个答案:

没有答案