how to add a dictionary to array in Mongodb - mongodb

I Use from Mongodb and have a collection like this:
{'name':'vahid','visited':[{id:1,'date':'1223123',noskhe:['a','d','h']]}
I want an update query to add {id:2,'date':'324324',noskhe:['d','n']} to visited array!
How I can get this query?

You need to use $push operator. It will append a new value to the array. Below is the example.
db.collection.update({"name":"vahid"},{$push:{ "visited": {id:2,'date':'324324',noskhe:['d','n']}}})

Related

pymongo - how to append values to array?

I am trying to create a database if it is not there already in mongo, and then create a collection in the database; then insert/update a document (which contains two keys, called erp and dataset whose value is a list of strings) in the collection. I know how to upsert a document like,
self.connection = pymongo.MongoClient(host=db_host, port=db_port)
self.connection.datasets.datasets.update_one({'erp': 'erp1'},
{'$set': {'data_set': ['database1']}},
upsert=True)
When the document is inserted into mongo for the 1st time, create a list with string(s) as values for the field 'data_set', but how to maintain/update the list of strings that whenever a new string comes in, just append the existing list for data_set.
UPDATE.
The working query
connection.erp_datasets.erp_datasets.update_one({'erp_name': 'erp1'},
{'$push': {'data_set': 'database1'}}, upsert=True)
I think what you're looking for a $push update operator.
The $push operator appends a specified value to an array.
self.connection.datasets.datasets.update_one(
{'erp': 'erp1'},
{'$push': {'data_set': 'database1'}}
)

$addtoset and append to end

I love the $addtoset option on MongoDB where you can add to an array of documents if the object doesn't already exist.
But in case, it exists, can I force it to go to the end of the array?
That is.
in this array:
[document1,document2,document3]
I would like to be able to do $addtoset:document2
[document1,document3,document2]
Is that something MongoDB supports?

Insert new Documents or modify an array field of existing document

Apologies if this is a re-post, but I wasn't able to quite get the query I want from the mongodb documentation examples.
Here's my issue. I am unable execute in a single query to either update an array_field of an existing document or add a new document and initialize the array_field with an initial value.
I can use findOne() with some conditional logic, and probably solve this, but I would think mongodb has an implementation of this use case
Here's the code so far:
#data_json = JSON document to be added to collection
collection.update_one({"json_id":data_json["json_id"], "_dashbd_id_":dashboard_id},{{"$addToSet": {"array_field":keyword}},{"$setOnInsert":data_json}}, upsert=True)
I'm querying by the json_id, and _dashbd_id_ from my collection. If it exists, then I intend to add the "keyword" to the array_field. If it doesn't exist, create a new document as data_json which include array_field = [keyword]
Any hints and suggestions are appreciated!
If I understood you correctly you want to update values in Database only if they do not exist as well as create new documents with arrays in them. Okay there is a way in mongodb which I will mention in this reply. I think you should know few commands first that will help you achieve similar result (again there is a simple way just read on)
Let me start with the first part:
to update an element in an array you use dot notation to the index example:
db.collection_name.update({"_id": id}, {'$set': {"array_name.indexNumber": value}})
say we have the following document in collection name cars
db.cars.findOne():
{
_id: 1
name: EvolutionX
brand: Mitsubish
year: 2012
mods: [ turbo, headlights ]
}
Say in the above example we want to update headlights with rearlights we do the following (using mongoshell you can drop quotes in key names, Not when using the array index though):
db.cars.update({id:1}, {$set:{"mods.1":"rearlights"}})
1 is the index to headlights.
Note and be careful here that if you did not use index inside of an array like
db.cars.update({id:1}, {$set:{"mods":"rearlights"}})
this will overwrite the existing document _id:1 and it will lose all other attributes or fields inside the document so it will result in the follow:
db.cars.findOne():
{
_id: 1
mods: [ rearlights ]
}
Now, say we want to add an element tires to mods array you can use $push as:
db.collection_name.update({"_id": id}, {'$push': {"array_name": value}})
so it will be
db.cars.update({"_id":1}, {"$push":{"mods":"tires"}})
now say instead of updating mods array you want to remove "headlights". In this case you use $pop
db.cars.update({"_id":1}, {"$pop":{"mods":"headlights"}})
Now with that in mind. The easy way: in mongodb to add to array only if element does not exist you can use $addToSet. I love this operator because it will only add to array if the element does not exist. Here is how to use it:
db.cars.update({"_id":1}, {"$addToSet":{"mods":"headlights"}})
Now if headlights is in the array it will not be added, else it will be added to the end of array.
Okay that is the first part of the question. The second part which is initializing a document with an array. Okay there are two thoughts here: the first is you do not have to. using the addToSet you can create the array if it does not exist as (assuming _id 2 exist but without mods array):
db.cars.update({"_id":2}, {"$addToSet":{"mods":"bonnet"}})
This will create the array if document _id:2 exist. Assuming _id:3 does not exist you will have plug in a third attribute called upsert
db.cars.update({"_id":3}, {"$addToSet":{"mods":"headlights"}}, {upsert:true})
this will create a third document with array mods with headlights inside of it and _id:3. Note though no other attributes will be added only the _id and mods array
the second thought is when you insert a new document you insert it with empty mods array as mod:[]
I hope that helps
suppose your data_json ,dashboard_id and keyword contain following detail.
dashboard_id = ObjectId("5423200e6694ce357ad2a1ac")
keyword = "testingKeyword"
data_json =
{
"json_id":ObjectId("5423200e6694ce357ad2a1ac"),
"item":"EFG222",
"reorder":false,
}
if you execute below query
db.collection_name.update({"json_id":data_json["json_id"], "_dashbd_id_":dashboard_id},{{"$addToSet": {"array_field":keyword}},{ upsert=True})
than it will push keyword to array_field if document exist or it will insert new document with following detail as below.
{
"_id":ObjectId("5sdvsdv6sdv694ce357ad2a1ac"),
"json_id":ObjectId("5423200e6694ce357ad2a1ac"),
"dashboard_id": ObjectId("sddfb6694ce357ad2a1ac")
"item":"EFG222",
"reorder":false,
"array_field":
[
"testingKeyword"
]
}

How can I populate a list in a MongoDB document?

I want to populate within a loop a MongoDB document's list, without overwriting the existing entries of the list. Something like python's append. Is there a command that does this?
You can use $Push operator.
If you need advance check Modifiers also.

Persist data as an (unordered) set in MongoDB

I am using MongoDB with node.js. Is it possible to persist data as an (unordered) set in MongoDB directly? Or do I have to either
persist them as an array and transform it into a set in JavaScript
or
persist them as an object in the form of {entry1: true, entry2: true, ...}
If I have to do it in either of the two ways above, which one is more efficient? Considering I need to add/remove items frequently, but rarely need to re-assign the whole set/array.
You can manipulate an array as a set in MongoDB... relevant operators include:
$addToSet - The $addToSet operator adds a value to an array only if the value is not in the array already.
$push - The $push operator appends a specified value to an array.
$pop - The $pop operator removes the first or last element of an array.
$pull - The $pull operator removes all instances of a value from an existing array.
$elemMatch - The $elemMatch operator matches more than one component within an array element.