草庐IT

javascript - 比较,添加,更新,删除 mongodb 数组上的元素

coder 2023-11-02 原文

MongoDB 的以下文档中需要有关更新、删除、添加、更新插入、删除等操作的帮助。 下面是存在于 temp 集合中的 MongoDB 文档。

{       

            "local_id" : "1841",

            "name_first" : "tiger", 

            "name_last" : "lion",

            "address" : [
              {
                "id" : 1,
                "address_type" : "Home", 
                "city" : "Delhi", 
                "country" : "", 
                "po_box" : ""
            }, 
            {
                "id" : 2, 
                "address_type" : "Work", 
                "city" : "", 
                "country" : "", 
                "po_box" : ""
            }
        ],

        "email" : [
            {
                "email_id" : "blah@gmail.com", 
                "id" : 1, 
                "type" : "Home"
            }, 
            {
                "email_id" : "Pearl1@gmail.com", 
                "id" : 2, 
                "type" : "Work"
            }
        ], 

 "phone_number" : [
            {
                "id" : 1, 
                "no" : "+911234567890", 
                "type" : "Mobile"
            },
            {
                "id" : 2, 
                "no" : "+917894561230", 
                "type" : "work"
            }
        ] 

     }`

现在我有一些像下面这样的文档,我想要查询来比较、添加、更新、删除我上面的​​文档。

`
    {       

           "local_id" : "1730",
           "name_first" : "lion", 
           "name_last" : "king", 

           "address" : [
                {
                    "id" : 1,
                    "address_type" : "Home", 
                    "city" : "Delhi", 
                    "country" : "India", 
                    "po_box" : "110041"
                }, 
                {
                    "id" : 2, 
                    "address_type" : "Work", 
                    "city" : "Delhi-NCR", 
                    "country" : "India", 
                    "po_box" : "110048"
                },
                {
                    "id" : 3, 
                    "address_type" : "Work", 
                    "city" : "Delhi-NCR", 
                    "country" : "Indai", 
                    "po_box" : "110048"
                }
            ],

            "email" : [
                {
                    "email_id" : "updatethis@gmail.com", 
                    "id" : 1, 
                    "type" : "Home"
                }, 
                {
                    "email_id" : "Pearl1@gmail.com", 
                    "id" : 2, 
                    "type" : "Work"
                },
                {
                    "email_id" : "addthisarray@gmail.com", 
                    "id" : 3, 
                    "type" : "personal"
                }
            ], 

            "phone_number" : [
                {
                    "id" : 1, 
                    "no" : "+911234567890", 
                    "type" : "Mobile"
                }
                /*second array not here so remove that array from that document*/
            ] 

        }`

最佳答案

您可以在服务器上保存函数,因为您可以调用该函数来获取差异,如下所示。

db.system.js.save({
    _id: "getupdatedArray",
    value: function(obj1, obj2) {
        var VALUE_CREATED = 'created';
        var VALUE_UPDATED = 'updated';
        var VALUE_DELETED = 'deleted';
        var VALUE_UNCHANGED = 'unchanged';

        function map(obj1, obj2) {
            if (isValue(obj1) || isValue(obj2)) {
                return {
                    type: compareValues(obj1, obj2),
                    old: obj1,
                    new: obj2
                };
            }

            var diff = {};
            for (var key in obj1) {
                if (isFunction(obj1[key])) {
                    continue;
                }

                var value2 = undefined;
                if ('undefined' != typeof(obj2[key])) {
                    value2 = obj2[key];
                }

                diff[key] = map(obj1[key], value2);
            }
            for (var key in obj2) {
                if (isFunction(obj2[key]) || ('undefined' != typeof(diff[key]))) {
                    continue;
                }

                diff[key] = map(undefined, obj2[key]);
            }

            return diff;
        }

        function compareValues(value1, value2) {
            if (value1 === value2) {
                return VALUE_UNCHANGED;
            }
            if ('undefined' == typeof(value1)) {
                return VALUE_CREATED;
            }
            if ('undefined' == typeof(value2)) {
                return VALUE_DELETED;
            }

            return VALUE_UPDATED;
        }

        function isFunction(obj) {
            return {}.toString.apply(obj) === '[object Function]';
        }

        function isArray(obj) {
            return {}.toString.apply(obj) === '[object Array]';
        }

        function isObject(obj) {
            return {}.toString.apply(obj) === '[object Object]';
        }

        function isValue(obj) {
            return !isObject(obj) && !isArray(obj);
        }

        return map(obj1, obj2);
    }
})

然后你可以像下面这样调用函数..

db.loadServerScripts();
getupdatedArray({"a": "abc"}, {"a": "a111", "b": "bbb"});

这会给你如下结果:

{ 
    "a" : {
        "type" : "updated", 
        "old" : "abc", 
        "new" : "a111"
    }, 
    "b" : {
        "type" : "created", 
        "old" : undefined, 
        "new" : "bbb"
    }
}

谢谢

萨蒂什·拉卡尼

关于javascript - 比较,添加,更新,删除 mongodb 数组上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41994414/

有关javascript - 比较,添加,更新,删除 mongodb 数组上的元素的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  7. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  8. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  9. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  10. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

随机推荐