How to remove array element in mongodb?

后端 未结 6 1446
情深已故
情深已故 2020-11-22 07:10

Here is array structure

contact: {
    phone: [
        {
            number: \"+1786543589455\",
            place: \"New Jersey\",
            createdAt: \         


        
相关标签:
6条回答
  • 2020-11-22 07:32

    Try the following query:

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

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

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

    0 讨论(0)
  • 2020-11-22 07:35

    In Mongoose: from the document:

    To remove a document from a subdocument array we may pass an object with a matching _id.

    contact.phone.pull({ _id: itemId }) // remove
    contact.phone.pull(itemId); // this also works
    

    See Leonid Beschastny's answer for the correct answer.

    0 讨论(0)
  • 2020-11-22 07:37

    If you use the Mongoose API and looking to pull a sub/child object: Read this document Don't forget to use save() when you're done editing otherwise the changes won't be saved to the database.

    0 讨论(0)
  • 2020-11-22 07:39

    To remove all array elements irrespective of any given id, use this:

    collection.update(
      { },
      { $pull: { 'contact.phone': { number: '+1786543589455' } } }
    );
    
    0 讨论(0)
  • 2020-11-22 07:44

    You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

    Collection.update({
        _id: parentDocumentId
      }, {
        $pull: {
          subDocument: {
            _id: SubDocumentId
          }
        }
      });
    

    This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

    Read more about pull here.

    0 讨论(0)
  • 2020-11-22 07:48

    This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

    db.collection.update(
      { _id: id },
      { $pull: { 'contact': { number: '+1786543589455' } } }
    );
    
    0 讨论(0)
提交回复
热议问题