$ lookup其中id字段的类型不同

时间:2016-06-09 17:52:10

标签: mongodb join mongodb-query aggregation-framework

我有两个系列:交易&帐户。

我需要将帐户加入交易,以便我可以在Accounts.acctType字段上进行分组。问题是Transactions.accountId的类型为'string',而Accounts._id的类型为'Int32'。

有没有办法解决这个问题,而无需更改Transactions.accountId类型?

当前查找代码:

$lookup: {
  from: 'accounts', 
  localField: accountId, 
  foreignField: '_id', 
  as: 'accountData'
}

我需要什么:

$lookup: {
  from: 'accounts', 
  localField: Number(accountId), //something like this
  foreignField: '_id', 
  as: 'accountData'
}

或者:

$lookup: {
  from: 'accounts', 
  localField: accountId, 
  foreignField: '_id.toString()', //or something like this
  as: 'accountData'
}

2 个答案:

答案 0 :(得分:1)

我最终进行了数据库更改,以使Id字段与数据类型内联。

答案 1 :(得分:0)

您可以$project您的文档并使用$toLower将“交易”“_id”字段转换为字符串。

db.Transaction.aggregate(
    [
        { "$project": { "_id": { "$toLower": "$_id" } } }, // You need include all the fields you want in your result.
        { "$lookup": {
            "from": "accounts", 
            "localField": "accountId", 
            "foreignField": "_id",
             "as": "accountData"
        }}
    ]
)
相关问题