mongodb找到多个参考文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongodb找到多个参考文件相关的知识,希望对你有一定的参考价值。
我在mongodb有一个数据库,它有两个集合:卡片和团队。我的卡片收集结构是:
{"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,number,page和团队信息(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
如何正确打印每张卡的所有信息?谢谢
答案
您可以通过以下方式之一进行操作。
迭代光标
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
}
光标的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}}
])
以上是关于mongodb找到多个参考文件的主要内容,如果未能解决你的问题,请参考以下文章