如何删除mongodb中的数组元素? [英] How to remove array element in mongodb?

查看:74
本文介绍了如何删除mongodb中的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是数组结构

contact: {
    phone: [
        {
            number: "+1786543589455",
            place: "New Jersey",
            createdAt: ""
        }
        {
            number: "+1986543589455",
            place: "Houston",
            createdAt: ""
        }

    ]
}

在这里,我只知道mongo id(_id)和电话号码(+1786543589455),我需要从文档中删除整个对应的数组元素.也就是说,电话数组中的零索引元素与电话号码匹配,因此需要删除相应的数组元素.

Here I only know the mongo id(_id) and phone number(+1786543589455) and I need to remove that whole corresponding array element from document. i.e zero indexed element in phone array is matched with phone number and need to remove the corresponding array element.

contact: {
    phone: [
        {
            number: "+1986543589455",
            place: "Houston",
            createdAt: ""
        }
    ]
}

我尝试了以下更新方法

collection.update(
    { _id: id, 'contact.phone': '+1786543589455' },
    { $unset: { 'contact.phone.$.number': '+1786543589455'} }
);

但是它从内部数组对象中删除number: +1786543589455,而不是从电话数组中的零索引元素中删除.用pull尝试也没有成功.

But it removes number: +1786543589455 from inner array object, not zero indexed element in phone array. Tried with pull also without a success.

如何在mongodb中删除数组元素?

How to remove the array element in mongodb?

推荐答案

尝试以下查询:

collection.update(
  { _id: id },
  { $pull: { 'contact.phone': { number: '+1786543589455' } } }
);

它将找到具有给定_id的文档,并将电话+1786543589455从其contact.phone阵列中移出.

It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array.

您可以使用$unset取消设置数组中的值(将其设置为null),但不能完全删除它.

You can use $unset to unset the value in the array (set it to null), but not to remove it completely.

这篇关于如何删除mongodb中的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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