Insert selective columns into collection using mongodb

南笙酒味 提交于 2020-06-16 17:24:30

问题


Wrote a trigger function that inserts full documents to my collection new_list when ever there is an insert into listingsAndReviews collection.

exports = function(changeEvent) {

    const fullDocument = changeEvent.fullDocument;

    const collection = context.services.get('Cluster0').db("sample_airbnb").collection("new_list");


    return collection.insertMany([fullDocument])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result;
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`));

};

Is there a way to select only particular required columns while inserting data into new_list collection. In this case i need to insert only name and cart_id and ignore others.

My sample collection column names :

name     - string
cart_id   - objectid
number - string
address - string

回答1:


You can extract your required properties from fullDocument and just insert this new object:

return collection.insertMany([{name: fullDocument.name, cart_id: fullDocument.cart_id }])

Afaik there's no other way to "filter" properties on the insert-methods. Also note that you can use insertOne here instead of insertMany as you're only inserting one document.



来源:https://stackoverflow.com/questions/62114892/insert-selective-columns-into-collection-using-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!