Paulo
Paulo

Reputation: 81

mongodb query by reference

I have the following database in mongodb:

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

It has a Card which has id of a team, and I'm trying to make a query to get the team of a specific Card. I tried:

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

However it is giving me a error in the second line:

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

Anyone knows how to resolve this problem? Thanks

Upvotes: 3

Views: 3259

Answers (1)

s7vr
s7vr

Reputation: 76004

You have few things incorrect here.

  1. You are referencing the incorrect field reference in $in operator. Should be {$in:team.Card.Team}
  2. You've incorrect field name for comparison. Should be Team._id

Complete code

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

You can also do the whole $lookup in one query.

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

Upvotes: 3

Related Questions