mongodb translation for sql INSERT…SELECT

后端 未结 4 1226
无人及你
无人及你 2021-01-05 10:11

How to simply duplicate documents from collectionABC and copy them into collectionB if a condition like {conditionB:1} and add a timestamp like ts_imported - without knowing

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 10:51

    I realise that this is an old question but...there is a better way of doing it now. MongoDB has now something called aggregation pipeline (v 3.6 and above, maybe some older ones too - I haven't checked). The aggregation pipeline allows you to do more complex things like perform joins, add fields and save documents into a different collection. For the OP's case, the pipeline would look like this:

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

    Relevant docs:

    • Aggregation pipeline
    • $out stage
    • some important limits

提交回复
热议问题