问题
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