$addtoset and append to end - mongodb

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?

Related

Push element in mongoDB, if it doesn't exist

I have many functions update with mongo
here is an example :
db.auto.update({'def.name':'AFFAIRES'},{$push:{
"covers":{$each: [{"a":'G06'},{"a":'G07'},{"a":'G03'},{"a":'G04'},{"a":'G07'},{"a":'G30'},{"a":'G34'},
{"cover":'G14'}]}}},{multi:true})
But,the problem, my collection may contain one of these variables "a", so i don't need to push it, and if it doesn't, i have to push it in the collection.
So my question is how to tell mongoDB to verify before the push, is it possible??
My query may contain other variables to push also.
Use $addToSet - The $addToSet operator adds a value to an array unless the value is already present. If the value is already present then the $addToSet does nothing to that array. $addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

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.

Does Mongo make a mistake like this?

Say I have a User Document, filled with arrays of ObjectIds.
They are references to documents in another collection.
I want to load all things from a particular user's array. So I do:
find({ _id: $in : someArrayOfObjectIds})
It's possible that certain references reference something that has been deleted.
So the resulting array of the above "find" call can be smaller then the someArrayOfObjectIds.
So for all the ObjectIds not found can I now safely assume that that document does not exist anymore, or can my query just fail to find a document (does mongo make a mistake).
Yes, you can safely assume that missing documents do not exist. By the way, your query is invalid. Should be this:
find({ _id: {$in : someArrayOfObjectIds}})
or can my query just fail to find a document
If it was possible, no one would use it. Pen and paper approach is a safer alternative that DB that makes such mistakes :)

how to add a dictionary to array in 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']}}})