paulodiovani
paulodiovani

Reputation: 1305

Move subdocument to another document

I'm modelling a mongodb database that will have categories and articles.

The most common use will be listing articles through the categories, so I plan to make the articles as subdocuments of categories:

//db.categories.find()

[{
  "id": 01,
  "name": "Some category",
  "articles: [{
    "article_id": 01,
    "title": "",
    "content": ""
  }]
}]

Sometimes, I might be moving articles from one category to another.

In a relational database, I should just update a foreign key, but in the above case, how can I move an article to another category?

Some details:

Upvotes: 1

Views: 1225

Answers (1)

Camilo
Camilo

Reputation: 1909

You need first to get the article, then remove (pull) the article from its current category and then add (push) it into its new category, like this:

first get the article (article_id:01) from the category with id:01 ...

then pull the article with article_id:01 from the category with id:01

db.categories.update(
    {"id" : 01, "articles.article_id" : 01},       // query
    {"$pull" : {"articles" : {"article_id" : 01}}} // pull
)

and then push that same article (article_id:01) into its new category with id:02,

db.categories.update(
    {"id" : 02},                                   // query
    {"$push" : {"articles" : {                     // push
                              "article_id": 01,
                              "title": "",
                              "content": ""
                             }
               }
    }
)

if you want the array in the new category to be sorted after the push you have to use $each and $sort (see here).

For more info on $pull check here and for more info on $push check here.

Upvotes: 1

Related Questions