2

$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 aggregate

4
  • you want to wirte to a new collection and also return you the data? if you want this one simple solution would be to query the newly created collection. Commented Nov 25, 2021 at 12:27
  • @Takis_, yes this is simple, but i query the database twice ! Commented Nov 25, 2021 at 14:03
  • 1
    yes ok, but the data are tranfered only once to you, i don't think that you can out+return cursor with one query the same time. Commented Nov 25, 2021 at 14:28
  • @Takis_ , yes indeed, I'm querying the newly created collection. Commented Nov 25, 2021 at 14:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The above query was run on a MongoDB v4.2.8 server and mongo shell client.
I didn't notice that the documentation mention this, thank you @prasad_

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.