[英]MongoDB Shell: How to Update a Collection from a Collection
I have two collections: links and children. 我有两个集合:链接和子集。
Links has values like this: 链接的值如下:
> db.links.find().pretty()
{ "_id" : ObjectId("567374999df36aeeda6f2a5f"), "EID" : 1, "CID" : 1 }
{ "_id" : ObjectId("567374999df36aeeda6f2a60"), "EID" : 1, "CID" : 3 }
{ "_id" : ObjectId("567374999df36aeeda6f2a61"), "EID" : 2, "CID" : 5 }
Children has values like this: 孩子们具有如下价值观:
{
"_id" : ObjectId("567382709df36aeeda6f2a7e"),
"CID" : 2,
"Cname" : "Mo",
"Age" : 11
}
{
"_id" : ObjectId("567382709df36aeeda6f2a7f"),
"CID" : 3,
"Cname" : "Adam",
"Age" : 13
}
{
"_id" : ObjectId("567382709df36aeeda6f2a80"),
"CID" : 4,
"Cname" : "Eve",
"Age" : 21
}
It seems like this should add EID to children where CID matches between links and children, but it does nothing. 似乎应该在链接和子级之间CID匹配的子级上添加EID,但是它什么也没做。
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({ id: doc1.CID });
if (doc2.CID == doc1.CID) {
doc1.EID = doc2.EID;
db.children.save(doc1);
}
});
This sets the value of EID in children to the value of EID from links where the value of CID in children == 14. 这会将子代中的EID值设置为来自子代中CID值== 14的链接的EID值。
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({},{_id: 0, CID: 1});
if (doc1.CID == 14) {
doc1.EID = doc1.CID;
db.children.save(doc1);
}
});
{
"_id" : ObjectId("567382709df36aeeda6f2a8a"),
"CID" : 14,
"Cname" : "George II",
"Age" : 12,
"EID" : 14
}
So, it seems like that the equality operation in Javascript (doc2.CID == doc1.CID) isn't working. 因此,似乎Javascript中的相等操作(doc2.CID == doc1.CID)无法正常工作。 Why won't this work? 为什么不起作用? I assume I have the syntax wrong or am using the wrong equality operation or operator? 我假设我的语法错误或使用了错误的相等运算符或运算符?
var doc2 = db.links.find({ id: doc1.CID });
doc2 here is a cursor, not the document itself. doc2是一个游标,而不是文档本身。 So you need to go through documents in the cursor. 因此,您需要浏览光标中的文档。
Try the following code: 尝试以下代码:
db.children.find().forEach(function (doc1) {
var doc2 = db.links.find({CID:doc1.CID}).forEach(function(doc2){
doc1.EID = doc2.EID;
db.children.save(doc1);
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.