[英]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
.它正在工作,但deleted-users
中的数据与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
):从 mongoDB 4.2 版开始,您可以使用$merge
在一个查询中执行此操作(对于旧版本使用$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.请注意,响应是: Fetched 0 record(s) in 0ms
,因为没有文档返回。 The document is instead inserted on the new collection.而是将文档插入到新集合中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.