Mongodb 在现有文档中添加一个具有特定位置的新字段 [英] Mongodb adding a new field in an existing document, with specific position
问题描述
我面临这个问题,我需要在现有文档的特定位置插入一个新字段.
I am facing this issue where I need to insert a new field in an existing document at a specific position.
示例文档:{名称":用户",年龄":21",名称":开发人员"}所以上面的一个是示例文件,我想要的是添加大学":ASU"在关键的年龄"下这可能吗?
Sample document: { "name": "user", "age" : "21", "designation": "Developer" } So the above one is the sample document,what I want is to add "university" : "ASU" under key "age" is this possible?
推荐答案
这里是你可以做的,先把文档当成一个dict
,然后我们来确定age<的索引/code> 然后我们会做一些索引,看下面:
Here's what you can do, first take the document as a dict
, then we will determine the index of age
and then we will do some indexing, look below:
>>> dic = { "name": "user", "age" : "21", "designation": "Developer" }
>>> dic['university'] = 'ASU'
>>> dic
{'name': 'user', 'age': '21', 'designation': 'Developer', 'university': 'ASU'}
添加了大学字段,现在我们将使用dic.items()
进行一些交换.
Added the university field, now we will do some exchanging by using 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'}
这篇关于Mongodb 在现有文档中添加一个具有特定位置的新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!