以下是我的Collection Called Run
var Run = [{
ID: 1,
Name: 'TestRun',
Comments: 'TestRun',
Status: [{
Cur: 'Active',
Mapper: {
Area: 'BH',
State: 'MH'
}
},
{
Cur: 'Inactive',
Mapper: {
Area: 'BO',
State: 'DU'
}
}]
}]
我希望在将'Area'
作为'BH'
获取所有数据时创建一个查询,以便我得到如下结果
Status: [{
Cur: 'Active',
Mapper: {
Area: 'BH',
State: 'MH'
}
}]
当我在mongodb提示符中触发此查询时:
db.Run.aggregate([
{$match: {'Status.Mapper.Area': 'BO'}},
{$project: {
Status:
{$filter: {
input: '$Status',
as: 'script',
cond: {$eq: ['$$script.Mapper.Area','BO']}
}},
_id: 0
}}
]).pretty();
结果如预期。但是,当我尝试使用Nodejs运行此查询时,它不返回任何结果。
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/exeexample';
mongodb.MongoClient.connect(uri, function(error, db) {
if(error) {
console.log(error);
process.exit(1);
}
db.collection('Run').find({ID: 1}).toArray(function(error, docs) {
if(error) {
console.log(error);
process.exit(1);
}
console.log('found docs:1 ');
docs.forEach(function(doc) {
console.log(JSON.stringify(doc));
db.collection('Run').aggregate([
{$match: {'Status.Mapper.Area': 'BO'}},
{$project: {
Status: {$filter: {
input: '$Status',
as: 'script',
cond: {$eq: ['$$script.Mapper.Area', 'BO']}
}},
_id: 0
}}
]).toArray(function(error, docs) {
console.log('found docs:2 ');
docs.forEach(function(doc) {
console.log('found docs:3 ');
console.log(JSON.stringify(doc));
});
});
process.exit(0);
});
});
});
该查询与我在MongoDB提示中使用的查询几乎相同。由于没有抛出任何错误,因此filter子句似乎有问题。 感谢您对此的帮助。
答案 0 :(得分:0)
process.exit(0);
错位,导致在异步聚合调用完成之前执行此语句。感谢JohnnyHK
更新后的代码如下:
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/exeexample';
mongodb.MongoClient.connect(uri, function(error, db) {
if(error) {
console.log(error);
process.exit(1);
}
db.collection('Run').find({ID: 1}).toArray(function(error, docs) {
if(error) {
console.log(error);
process.exit(1);
}
console.log('found docs:1 ');
docs.forEach(function(doc) {
console.log(JSON.stringify(doc));
db.collection('Run').aggregate([
{$match: {'Status.Mapper.Area': 'BO'}},
{$project: {
Status: {$filter: {
input: '$Status',
as: 'script',
cond: {$eq: ['$$script.Mapper.Area', 'BO']}
}},
_id: 0
}}
]).toArray(function(error, docs) {
console.log('found docs:2 ');
docs.forEach(function(doc) {
console.log('found docs:3 ');
console.log(JSON.stringify(doc));
});
process.exit(0); **//Moved**
});
});
});
});