我在mongodb中有一个数据库,它有两个集合: cards 和 teams 。 我的卡集合结构是:
{"Card":{"_id":{"$oid":"5a46626e150ed3f847f01bac"},"Number":1,"Page":1,"Team":[{"$oid":"5a465ca9150ed3f847f01b92"}]}}
{"Card":{"_id":{"$oid":"5a466d96150ed3f847f01bad"},"Number":18,"Page":6,"Team":[{"$oid":"5a465ca9150ed3f847f01b92"}]}}
{"Card":{"_id":{"$oid":"5a466de6150ed3f847f01bae"},"Number":35,"Page":8, "Team":[{"$oid":"5a465ca9150ed3f847f01b92"}]}}
和我的团队集合结构是:
{"Team":{"_id":{"$oid":"5a465ca9150ed3f847f01b92"},"Name":"NA","Coach":"NA"}}
我想打印所有卡片信息,也就是说,对于每张卡片,我想要打印它的ID,编号,页面和团队信息(id,name和coach)。 我试过了:
var team = db.cards.find()
while(team.hasNext()){team_data = db.teams.find({"Team._id":{$in:team.Cards.Team}}).toArray()}
但它给了我:
2018-01-02T18:35:57.588+0000 E QUERY [thread1] TypeError: team.Cards is undefined :
@(shell):1:62
然后我试了试:
var team = db.cards.find()
while(team.hasNext()){team_data = db.teams.find({"Team._id":{$in:team.Team}}).toArray()}
它给了我:
2018-01-02T18:36:21.620+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:35
最后我尝试了:
var team = db.cards.find()
team.forEach(team_data = db.teams.find({"Team._id":{$in:team.Team}}).toArray())
但它也不起作用:
2018-01-02T18:28:28.345+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
如何正确打印每张卡的所有信息? 感谢
答案 0 :(得分:2)
您可以通过以下方式之一进行操作。
迭代光标
var teamCursor = db.cards.find();
while (teamCursor.hasNext()) {
var team = teamCursor.next();
var team_data = db.teams.find({"Team._id":{$in:team.Card.Team}}).toArray();
// format output here
}
Cursor的foreach
db.cards.find().forEach( function(team) {
var team_data = db.teams.find({"Team._id":{$in:team.Card.Team}}).toArray();
// format output here
});
在3.6(首选)中使用聚合
db.cards.aggregate([
{"$lookup":{
"from":"teams",
"localField":"Card.Team",
"foreignField":"Team._id",
"as":"team_data"}
},
{"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
{"$arrayElemAt":["$team_data",0]},
"$$ROOT"
]}
}
},
{"$project":{"team_data":0}}
])