假设我有一家公司收藏:
[{
name: 'x',
code: 'a',
},
{
name: 'y',
code: 'b',
}]
我想找到代码为“ a”的公司,并将其插入到另一个名为project的集合中。我写了这样的东西:
var collectionP = db.collection('projects');
var collectionC = db.collection('company');
var foundCompany = collectionC.find({code: 'a'});
db.collectionP.insert(name: 'project1', company: foundCompany);
这行不通。任何的想法?
调用find
返回一个游标,而不是结果集。
如果期望多个结果,则可以选择在游标上进行迭代:
var foundCompany = collectionC.find({code: 'a'});
foundCompany.forEach(function(fc) {
db.collectionP.insert(name: 'project1', company: fc);
}
或将所有结果合并到一个文档中,则将其转换为数组:
var foundCompany = collectionC.find({code: 'a'}).toArray();
db.collectionP.insert(name: 'project1', company: foundCompany);
或者,如果您只希望与单个公司匹配,请使用您的语言使用findOne或同等的语言:
var foundCompany = collectionC.findOne({code: 'a'});
db.collectionP.insert(name: 'project1', company: foundCompany);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句