2014-01-28 134 views
0

我有一个document调用Mapping,它有一个_id和一个叫Mappings的对象数组。 我有另一个collectionNewMappings。对于NewMappings中的每个_id,我需要在Mappings (of Mapping collection)的数组内搜索并返回Mapping_id基于另一个搜索MongoDB集合

我写了这样的东西,但它没有返回任何东西。

var d=db.NewMappings.find(); 
d.forEach(function(item){ 
    db.matching.find({Mappings: {$elemMatch : {TargetId: item._id}}}) 
}) 

然而,该查询返回的值

var d=db.NewMappings.find(); 
db.matching.find({Mappings: {$elemMatch : {TargetId: d[0]._id}}}) 

我缺少的东西? 请帮帮我。我在黑暗中。提前致谢。

+0

在您使用的forEach,你正在创建一个不返回值的函数的代码。您需要存储或打印它。 –

+0

你可以添加一段代码来显示吗?谢谢。 – user3245595

回答

0

的一种方式,如果你只是想看到的结果是:

var d=db.NewMappings.find(); 
d.forEach(function(item){ 
    db.matching.find({Mappings: {$elemMatch : {TargetId: item._id}}}).forEach(printjson) 
}) 

您还可以使用aggregation framework

+1

谢谢。我认为第二次查找只返回一个文档。我添加了forEach部分,它工作。 – user3245595

0

听起来你试图做一个加入,这是不明确在MongoDB中受支持。您需要使用一些聚合函数来平整数据或mapreduce。

下面是一个使用MapReduce的重组信息的一个例子: http://cookbook.mongodb.org/patterns/pivot/

相关问题