Mongodb adding a new field in an existing document, with specific position

2024/11/15 19:46:03

I am facing this issue where I need to insert a new field in an existing document at a specific position.

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?

Answer

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'}

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'}
https://en.xdnf.cn/q/119281.html

Related Q&A

how to check every 3 x 3 box in sudoku?

I am trying to build a sudoku solver without much googling around. Right now, I am working on a function to test whether the board is valid, which I will use later in a loop. This is what the function …

multiple model accuracy json result format using python

I am building a multiple model and i am getting results with 7 models accuracy, i need those results with a proper json format.My multiple model building code will be like thisseed = 7"prepare mod…

Calculate Time Difference based on Conditionals

I have a dataframe that looks something like this (actual dataframe is millions of rows):ID Category Site Task Completed Access Completed1 A X 1/2/22 12:00:00AM 1/1/22 12:00:00 AM1 A Y 1/3/22 12:00:00A…

Cannot open jpg images with PIL or open()

I am testing to save ImageField in Django, but for some reason all the *.jpg files Ive tried dont work while the one png I had works. Using django shell in WSL VCode terminal. python 3.7 django 3.0 pil…

how to delete tensorflow model before retraining

I cant retrain my image classifier with new images, I get the following error:AssertionError: Export directory already exists. Please specify a different export directory: /tmp/saved_models/1/How do I …

Use beautifulsoup to scrape a table within a webpage?

I am scraping a county website that posts emergency calls and their locations. I have found success webscraping basic elements, but am having trouble scraping the rows of the table. (Here is an example…

Encrypt folder or zip file using python

So I am trying to encrypt a directory using python and Im not sure what the best way to do that is. I am easily able to turn the folder into a zip file, but from there I have tried looking up how to en…

Use Python Element Tree to parse xml in ASCII text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Time series plot showing unique occurrences per day

I have a dataframe, where I would like to make a time series plot with three different lines that each show the daily occurrences (the number of rows per day) for each of the values in another column. …

Problem accessing indexed results two stage stochastic programming Pyomo

When running a stochastic programming problem in Pyomo, the resulting solution works only when running 10 precisely the same scenarios but the results remain zero when running different scenarios. I ai…