sql >> Databáze >  >> NoSQL >> MongoDB

Mongodb přidání nového pole do existujícího dokumentu s konkrétní pozicí

Zde je to, co můžete udělat, nejprve vzít dokument jako dict , pak určíme index age a pak provedeme nějakou indexaci, podívejte se níže:

>>> dic = { "name": "user", "age" : "21", "designation": "Developer" }
>>> dic['university'] = 'ASU'
>>> dic
{'name': 'user', 'age': '21', 'designation': 'Developer', 'university': 'ASU'}

Přidáno pole univerzity, nyní provedeme nějakou výměnu pomocí dic.items() .

>>> i = list(dic.items())
>>> i
[('name', 'user'), ('age', '21'), ('designation', 'Developer'), ('university', 'ASU')]
#now we will acquire index of 'age' field
>>> index = [j for j in range(len(i)) if 'age' in i[j]][0] 
#it will return list of single val from which we will index the val for simplicity using [0]
>>> index
1
#insert the last element ('university') below the age field, so we need to increment the index
>>> i.insert(index+1,i[-1])
# then we will create dictionary by removing the last element which is already inserted below age
>>> dict(i[:-1])
{'name': 'user', 'age': '21', 'university': 'ASU', 'designation': 'Developer'}



  1. Ukládání UTC a místního data a času v Mongo

  2. Jak použít název dynamické proměnné v JavaScriptu bez eval pro aktualizaci MongoDB?

  3. Jak vytvářet, zobrazovat a pouštět sbírky v MongoDB

  4. Přírůstkové pole k existující kolekci