ada*_*lev 3 mongodb mongodb-query aggregation-framework node-mongodb-native
长期倾听者,第一次来电。
我正在使用节点驱动程序在 mongo 上执行聚合命令,并且该$out阶段似乎仅在链接某些方法时才会生效。
我想aggregate()用 $out 作为管道的最后阶段进行调用,然后回调。目前,它仅在我链接next()或toArray()令人厌烦的情况下才有效,因为方法签名是聚合(管道,选项,回调)。
为了清楚起见,下面的示例进行了简化。
在这里,我使用回调,$out 不生效(即 newNames 未创建,但回调被执行)。我正在重构几个月前的东西,这之前是有效的(节点驱动程序的版本 2.2.33):
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
], (err, result) => {
// result is an AggregationCursor
callback();
});
Run Code Online (Sandbox Code Playgroud)
如果我不添加回调而是链接 next() ,则 $out 阶段会生效
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
])
.next((err, result) => {
// result is null, why?
callback();
});
Run Code Online (Sandbox Code Playgroud)
如果你链接到Array它也可以工作:
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
])
.toArray((err, result) => {
// result is an empty array (i.e. the resulting docs), OK, makes sense
callback();
});
Run Code Online (Sandbox Code Playgroud)
所以我想我一定是误解了 Promise 与回调,但是如果我使用 close() ,它不会生效,它是链接的,结果又回到了 AggregationCursor:
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
])
.close((err, result) => {
// result is an AggregationCursor
callback();
});
Run Code Online (Sandbox Code Playgroud)
阅读一些对问题的回复,似乎聚合游标与结果文档是预期的。但我不明白为什么当我进入回调或链 close() 时 $out 没有生效。
小智 7
我自己也遇到了这个问题。我调用了cursor.next(),直到收到空值并且$out 聚合起作用。使用 async/await 可以让这变得简单。如果没有这些,这看起来可能会变得非常混乱。
var cursor = await db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
]);
var next = null;
do {
next = await cursor.next();
} while (next != null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |