0

I have created a pipeline that creates a usage report by user.
I wrote all the pipelines and tried to do a final merge, but I noticed that there was no field with a unique id to write at "on".

I tried to use $out, but I couldn't because I want the collection to keep stacking without being covered.

I just want to keep inserting new ObjectId for my results.

$merge: {
  into: "Report",
  on: "?? don't have uniq field ... why we can't just make newId for each new documents!!",
  whenMatched: "i just want to keep insert",
  whenNotMatched: "insert",
}

My final documents looks like

name:"개발"
userId: ObjectId(6049eeb428398a115cf83404)
purchaseBundleCnt:230
purchaseBundlePriceSum:5769500
yyyymmdd:20211001

After considering several methods, I found that by concating yyyymmdd and userId, can create a unique id. But because it is not an ObjectID.Type, it is not accepted in on.

minjae kim
  • 139
  • 2
  • 9
  • [Does this answer help](https://stackoverflow.com/a/70029031/316310)? Otherwise, since you're making a report per user, it seems, perhaps you could use the userId as the unique key, or perhaps a compound index of `_id: { userId: ..., yyyymmdd: ... }`. – RickN Nov 30 '21 at 13:05
  • @RickN yes it seems helpful for me ! I will try thank you! – minjae kim Nov 30 '21 at 13:18

1 Answers1

0

I don't know if I got you right, but if you wanna generate a unique id for on property, you can try the following:

You can find the ObjectId constructor on require('mongoose').Types.

var mongoose = require('mongoose');

$merge: {
  into: "Report",
  on: mongoose.Types.ObjectId()
}

with Mongoose 6 you must prefix the call with new:

$merge: {
  into: "Report",
  on: new mongoose.Types.ObjectId()
}

I didn't give it a try, but I hope this would work for you.

root
  • 151
  • 5