使用mongodb将选择性列插入集合 [英] Insert selective columns into collection using mongodb

查看:82
本文介绍了使用mongodb将选择性列插入集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写了一个触发函数,当 listingsAndReviews 集合中有插入内容时,该函数将完整文档插入到我的集合 new_list

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}`));

};

有没有一种方法可以在将数据插入new_list集合时仅选择特定的必需列。
在这种情况下,我只需要插入名称和cart_id并忽略其他内容。

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.

我的样本收集列名称:

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


推荐答案

您可以从 fullDocument 中提取所需的属性,然后插入这个新对象:

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没有其他方法可以在插入方法上过滤属性。
还请注意,您可以在这里使用 insertOne 代替 insertMany ,因为您只插入一个文档。

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.

这篇关于使用mongodb将选择性列插入集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆