【问题标题】:MongoDB set a sub item in an arrayMongoDB在数组中设置子项
【发布时间】:2013-11-01 07:31:56
【问题描述】:

在收藏中

{ _id: 123,
    category: 1,
    desc: 'desc',
    price: 99,
    item: 
     [ { two: '24',
     three: '48' },
       { two: '',
      three:''},
       { two: '33',
      three:'24'},
        ] } ,
{ _id: 121,
    category: 1,
    desc: 'desc',
    price: 99,
    item: 
     [ { two: '24',
     three: '58' },
       { two: '',
      three:''},
       { two: '35',
      three:'54'},
        ] } 

如何将 item.two = '24' 的所有记录的值 'two' 设置为 null

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    使用位置运算符$ 从匹配搜索查询的项目数组中更新文档:

    update({ "item.two" : "24" }, 
           { $set : { "item.$.two" : "" }}, false, true);
    

    如果要从数组文档中删除该字段,请使用$unset 运算符:

    update({ "item.two" : "25" }, 
           { $unset : { "item.$.two" : "" }}, false, true);
    

    【讨论】:

    • 感谢您的回复。这是完美的,工作正常:)
    • update({ "item.two" : { $in : ['24','30']} }, { $unset : { "item.$.two" : "" }} , 假的, 真);不管用。你能帮帮我吗? :) 如果一个集合中有多个包含两个=24 的项目,我该如何更新它
    • @NisanthSojan 我认为在单个查询中不可能更新多个数组项。您可以查看herehere 寻找解决方法。
    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2014-06-26
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多