如何在mongo shell forEach中运行嵌套查询



我很难弄清楚如何在mongoshell中对集合的每个成员运行查询。以下是我迄今为止的收获。

rs0:SECONDARY> db.activity.find().limit(10).forEach(
...   function( activity ) {
...     var count = db['da-plan'].find( { activities: activity._id.toString() } ).count();
...     print(
...       "_id: "
...       + activity._id
...       + ", daPlanId: "
...       + activity.daPlanId
...       + ", count: "
...       + count);
...   }
... );
_id: 5b045caf87207c00017d4697, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d4698, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d4699, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469a, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469b, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469c, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469d, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469e, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d469f, daPlanId: 5b045caf87207c00017d4694, count: 0
_id: 5b045caf87207c00017d46a0, daPlanId: 5b045caf87207c00017d4694, count: 0
rs0:SECONDARY> // for the first element at least, the count should not have been 0
rs0:SECONDARY> db['da-plan'].find( { activities: '5b045caf87207c00017d4697' } ).count();
1

我的嵌入式查询似乎不起作用,因为它总是产生零的计数,但当独立执行时,计数通常为非零。我做错了什么?

如何在mongo shell的forEach循环中执行嵌套查询?

_idObjectId,而不是String。因此toString()没有生成count查询所需的内容。将其更改为activity._id.valueOf()解决了问题。

rs0:SECONDARY> db.activity.find().limit(10).forEach(
...   function( activity ) {
...     var count = db['da-plan'].find(
...       { activities: activity._id.valueOf() }
...     ).count();
...     print(
...       "_id: "
...       + activity._id
...       + ", daPlanId: "
...       + activity.daPlanId
...       + ", count: "
...       + count);
...   }
... );
_id: 5b045caf87207c00017d4697, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d4698, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d4699, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469a, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469b, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469c, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469d, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469e, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d469f, daPlanId: 5b045caf87207c00017d4694, count: 1
_id: 5b045caf87207c00017d46a0, daPlanId: 5b045caf87207c00017d4694, count: 1

最新更新