sql >> Base de Datos >  >> NoSQL >> MongoDB

Mongodb agregando un nuevo campo en un documento existente, con una posición específica

Esto es lo que puede hacer, primero tome el documento como un dict , entonces determinaremos el índice de age y luego haremos un poco de indexación, mira a continuación:

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

Se agregó el campo universitario, ahora haremos algunos intercambios usando 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'}