mongodb translation for sql INSERT…SELECT

后端 未结 4 1197
无人及你
无人及你 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:26

    You can use javascript from mongoshell to achieve a similar result:

    db.collectionABC.find({ conditionB: 1 }).
    forEach( function(i) { 
      i.ts_imported = new Date();
      db.collectionB.insert(i);
    });
    
    0 讨论(0)
  • 2021-01-05 10:33

    Mongodb does not have that kind of querying ability whereby you can (inside the query) insert to another collection based upon variables from the first collection.

    You will need to pull that document out first and then operate on it.

    You could technically use an MR for this but I have a feeling it will not work for your scenario.

    0 讨论(0)
  • 2021-01-05 10:34

    It seems that this works in the context of sequence generation http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题