简体   繁体   中英

mongoDB find from one collection and save in another collection

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM