Home > OS >  mongoDB find from one collection and save in another collection
mongoDB find from one collection and save in another collection

Time:06-12

I want to find a user from my user collection then inserting this exact user in another collection that have the same schema.

Here is my implementation: (Controller)

const user = await User.findOne({ _id: id });
if (user) {
  const deletedUser = await DeletedUser({
    ...user,
  });
  deletedUser.save();
}

(Schema)

const User = tazweedDBConnection.model('users', userSchema, 'users');
const DeletedUser = tazweedDBConnection.model(
  'deleted-users',
  userSchema,
  'deleted-users'
);
module.exports = { User, DeletedUser };

It's working but the data in deleted-users is not like the one in user. I only get the default values in the schema.

CodePudding user response:

Since mongoDB version 4.2, you can use $merge to do it in one query (for older version use $out):

User.aggregate([
 {$match: {_id: id}},
 {$merge: {into: "newCollection"}}
])

Notice that the response is: Fetched 0 record(s) in 0ms, since no document is coming back. The document is instead inserted on the new collection.

  • Related