mongodb翻译为sql INSERT ... SELECT

led*_*edy 6 mysql mongodb

如何简单地从collectionsABC复制文档并将其复制到collectionB中,如果条件如{conditionB:1}并添加时间戳如ts_imported - 不知道原始文档中包含的详细信息?

我找不到类似于mysql的mongodb的简单等价物 INSERT ... SELECT ...

Eri*_*ric 14

您可以使用mongoshell中的javascript来实现类似的结果:

db.collectionABC.find({ conditionB: 1 }).
forEach( function(i) { 
  i.ts_imported = new Date();
  db.collectionB.insert(i);
});
Run Code Online (Sandbox Code Playgroud)


Rom*_*lak 10

我意识到这是一个老问题,但是……现在有更好的方法。MongoDB 现在有一种叫做聚合管道的东西(v 3.6 及更高版本,也许还有一些旧的 - 我没有检查过)。聚合管道允许您执行更复杂的操作,例如执行连接、添加字段和将文档保存到不同的集合中。对于 OP 的情况,管道将如下所示:

var pipeline = [
    {$match: {conditionB: 1}},
    {$addFields: {ts_imported: ISODate()}},
    {$out: 'collectionB'}
]
// now run the pipeline
db.collectionABC.aggregate(pipeline)
Run Code Online (Sandbox Code Playgroud)

相关文档: