$out stage
According to the mongodb documentation
$out | Writes the resulting documents of the aggregation pipeline to a collection. To use the $out stage, it must be the last stage in the pipeline. |
---|
the $out stage is working perfectly and writing new collection, i'm using append function
.append({ $out: "aggr_out" })
to place it in the last stage.
The current behavior
- Saving new collection to the database
- Returning an empty array in the
callback
function
Expected behavior
- Return the aggregate result
Versions of Node.js, Mongoose, and MongoDB
- node.js v14.17.3 (LTS)
- mongoose v5.13.13
- mongoDB
- db version v4.0.23
- git version: 07c6611b38d2aacbdb1846b688db70b3273170fb
- build environment:
- distmod: debian92
- distarch: x86_64
- target_arch: x86_64
Code
CodePudding user response:
It is the expected behavior; i.e., when you use the $out
stage in an aggregation query the result of the query is written to the collection name specified in the $out
. And, the query returns an empty cursor.
For example, take a collection with a document:
{ _id: 1, stuff: [ "bananas", "whales" ] }
The query:
var cur = db.collection.aggregate([
{ $out: "new_collection" }
])
When you run this query (in mongo
shell), the console output is an empty cursor (though the new_collection
is created).
cur.hasNext()
returns false
(indicates there are no result documents in the cursor).
Mongoose query returns an array (not a cursor). So, you see an empty array in the callback result value. This is to be expected.
Reference: db.collection.aggregate() - see the Returns section.
If the pipeline includes the $out operator, aggregate() returns an empty cursor.