A
A
Andrew2016-06-29 21:41:28
MongoDB
Andrew, 2016-06-29 21:41:28

How to update an object in an array in an object or insert it if it's not there?

There is a DB parents-children.
Parents' names are unique. The names of children are unique to the parent.

{
  parent: "Ivan Ivanov",
  children: [{
    {name: Masha,
     age: 20,
     sex: female
    },
    {name: Vasya,
     age: 23,
     sex: female
  }]
}

Let's say the child has changed gender - how to update the information if there is already a child with the same name, but if not, then insert it?
db.parents.update({parent: "Ivan Ivanov"}, {$addToSet: {children: {name: Vasya, age: 23, sex: male}}}, {upsert:true});

- just adds another child Vasya.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly, 2016-06-29
@taliban

https://docs.mongodb.com/manual/reference/method/d...
upsert: true
upd:

db.parents.update(
  {"$and": [
    {
      parent: "Ivan Ivanov"
    },
    {
      "children.name": Vasya
      "children.age": 23
      "children.sex": "male"
    }
  ]},
  {
    "children.sex": "female"
    // тут, если не сработает, попробуйте полностью обьект заменить
  }
)

something like this, also try
upd2:
the more I work with monga, the more I like it, here is a 100% working version:
db.getCollection('parents').update({"parent": "Ivan Ivanov", "children.age": 23}, {"$set": {"children.$.sex": "male"}})

L
lega, 2016-06-29
@lega

The names of children are unique to the parent.

If you need uniqueness within a document, use a dictionary (object) instead of an array.
Judging by this structure, there will either be duplicates of children in the database, or the children will not have children and there will be only one parent, if children need to be referenced, then it is better to store them in separate documents.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question