2016-05-30 18 views
0

ich folgende mongodb Sammlung Beiträge mit Dokument wie folgt benannt habe:wie ein Element aus einem MongoDB Array Dokumenten entfernen

{ 
    "_id" : "111", 
    "comments" : [ 
     { 
      "replyPost" : "aaaa", 
      "username" : "John Doe" 
     }, 
     { 
      "replyPost" : "bbbb", 
      "username" : "Jane Smith" 
     }, 
     { 
      "replyPost" : "cccc", 
      "username" : "Jane Smith" 
     }, 
     { 
      "replyPost" : "dddd", 
      "username" : "Jane Smith" 
     } 
    ] 
} 

Ich versuche, ein Array-Element mit dem replyPost zu entfernen: „cccc“, so dem Ergebnis wäre:

{ 
    "_id" : "111", 
    "comments" : [ 
     { 
      "replyPost" : "aaaa", 
      "username" : "John Doe" 
     }, 
     { 
      "replyPost" : "bbbb", 
      "username" : "Jane Smith" 
     }, 
     { 
      "replyPost" : "dddd", 
      "username" : "Jane Smith" 
     } 
    ] 
} 

ich habe versucht, .update Methode mit $ beziehen ziehen Dokument MongoDB https://docs.mongodb.com/manual/reference/operator/update/pull/

Posts.update(
    {_id: this._id}, 
    { $pull: { comments: { replyPost:"cccc"} } } 
); 

die scheinen nicht zu funktionieren. Kann jemand das Problem sehen?

+0

Ich habe überprüft und Abfrage funktioniert in mongoshell – styopdev

Antwort

0

Sehen Sie, wenn Sie die richtige _id bekommen. Es ist im String-Format.

Ich versuchte das gleiche in Mongo Shell. Es hat für mich funktioniert.

Hier das Protokoll:

> db.posts.insert({ 
...  "_id" : "111", 
...  "comments" : [ 
...   { 
...    "replyPost" : "aaaa", 
...    "username" : "John Doe" 
...   }, 
...   { 
...    "replyPost" : "bbbb", 
...    "username" : "Jane Smith" 
...   }, 
...   { 
...    "replyPost" : "cccc", 
...    "username" : "Jane Smith" 
...   }, 
...   { 
...    "replyPost" : "dddd", 
...    "username" : "Jane Smith" 
...   } 
...  ] 
... }) 
WriteResult({ "nInserted" : 1 }) 
> db.posts.update({_id:'111'},{$pull:{comments:{replyPost:'cccc'}}}) 
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 
> db.posts.findOne() 
{ 
     "_id" : "111", 
     "comments" : [ 
       { 
         "replyPost" : "aaaa", 
         "username" : "John Doe" 
       }, 
       { 
         "replyPost" : "bbbb", 
         "username" : "Jane Smith" 
       }, 
       { 
         "replyPost" : "dddd", 
         "username" : "Jane Smith" 
       } 
     ] 
} 
0

Wenn Sie Mungo verwenden, können Sie tun:

db.posts.remove({replyPost: 'cccc'}, function(err) { 
}) 

Der erste Parameter jeder Mungo Abfrage Ausdruck sein kann. Alle Übereinstimmungen werden aus db entfernt.

Siehe mongoose remove

+0

Diese Abfrage tut nichts, wenn Sie '' bedeuten db.posts.remove ({ "Kommentare. replyPost ": 'cccc'}, function (err) { })' 'Es wird das ganze Dokument entfernt, nicht nur ein einzelner Kommentar. – styopdev

0

Works Getestet Fein:

Posts.update((
    {"_id" : "111"}, 
    { $pull: {comments: {"replyPost" : "cccc"}} }, 
    { multi: true } 
) 
Verwandte Themen