通过引用查询mongodb

时间:2018-01-02 15:32:08

标签: mongodb mongodb-query

我在mongodb中有以下数据库:

{"Team":{"_id":{"$oid":"5a465ca9150ed3f847f01b92"},"TeamName":"NA"}}
{"Card":{"_id":{"$oid":"5a46626e150ed3f847f01bac"},"Number":1,"Page":1,"Team":[{"$oid":"5a465ca9150ed3f847f01b92"}]}}

它有一张卡片,其中包含一个团队ID,我正在尝试进行查询以获取特定卡片的团队。我试过了:

Team = db.test.findOne({"Card.Number":1})
Team_data = db.test.find({_id:{$in:team.Team}}).toArray()

然而它在第二行给我一个错误:

2018-01-02T15:22:21.112+0000 E QUERY    [thread1] Error: error: {
        "ok" : 0,
        "errmsg" : "$in needs an array",
        "code" : 2,
        "codeName" : "BadValue"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCommandCursor@src/mongo/shell/query.js:717:1
DBQuery.prototype._exec@src/mongo/shell/query.js:117:28
DBQuery.prototype.hasNext@src/mongo/shell/query.js:288:5
DBQuery.prototype.toArray@src/mongo/shell/query.js:337:12
@(shell):1:13

任何人都知道如何解决这个问题? 感谢

1 个答案:

答案 0 :(得分:1)

这里有一些不正确的事情。

  1. 您在$in运算符中引用了错误的字段引用。应该是{$in:team.Card.Team}
  2. 您的字段名称不正确,无法进行比较。应该是Team._id
  3. 完整代码

    team = db.test.findOne({"Card.Number":1}) 
    Team_data = db.test.find({"Team._id":{$in:team.Card.Team}}).toArray()
    

    您还可以在一个查询中执行整个$lookup

    db.test.aggregate([
      {"$match":{"Card.Number":1}},
      {
        "$lookup": {
          "from": "test",
          "localField": "Card.Team",
          "foreignField": "Team._id",
          "as": "team_data"
        }
     },
     { "$project": {"team_data":1} }
    ])