Home > Back-end >  MongoDB query updateOne doesn't find match
MongoDB query updateOne doesn't find match

Time:08-08

I don't understand what I am doing wrong.

The database intention:

category : {
    name : category_name, subcategory : [{
        name : subcategory_name, skill : [{
            name : skill_name
        }]
    }]
}

Category have an array of subcategories, which also have an array of skills.

So I can have many subcategories into a category, and each subcategory can have many skills.

The following query creates the category "Web development" with 2 subcategories, "Frontend" and "Backend", with their respective skills

db.skills.insertOne({ category : { cat_name : "Web development", subcategory : [{ subcat_name : "Frontend", skills : [{ skill_name : "Angular", skill_name : "Css"}]}, { subcat_name : "Backend", skills : [{ skill_name : "Nodejs", skill_name : "Express" }]}]}})

The problem: the following query returns { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 } which means that it didn't find the category "Web development"

db.skills.updateOne( { category : { cat_name : "Web development" }}, { $set: { category : { cat_name : "Not web development" }}} )

Same for the next query, it didn't find the subcategory

db.skills.updateOne( { subcategory : { subcat_name : "Frontend" }}, { $push: { skills : { skill_name : "SASS" }}} )

db.skills.find() returns the first insertOne but doesn't have the first skills, "Angular" from frontend subcategory and "Nodejs" from the backend subcategory, which makes no sense:

{ "_id" : ObjectId("62effb72d6fbc7d2a7d756d5"), "category" : { "cat_name" : "Web development", "subcategory" : [ { "subcat_name" : "Frontend", "skills" : [ { "skill_name" : "Css" } ] }, { "subcat_name" : "Backend", "skills" : [ { "skill_name" : "Express" } ] } ] } }

CodePudding user response:

Changing your schema a bit to what I think you intend to do, here are a couple of update commands that show how you can accomplish what you want. Note the use of "dot notation" and "arrayFilters". These aren't the only ways to do this, just one of the ways.

db.collection.update({
  "categories.cat_name": "Web development"
},
{
  "$push": {
    "categories": {
      "cat_name": "Not web development"
    }
  }
})

Try it on mongoplayground.net.

Here's how you can "$push" a new skill.

db.collection.update({
  "categories.cat_name": "Web development"
},
{
  "$push": {
    "categories.$[catElem].subcategories.$[subcatElem].skills": "SASS"
  }
},
{
  "arrayFilters": [
    {"catElem.cat_name": "Web development"},
    {"subcatElem.subcat_name": "Frontend"}
  ]
})

Try it on mongoplayground.net.

  • Related