Some MongoDB questions - mongodb

I'm new to MongoDB and Meteor. I have checked the official docs but seems they didn't do good job. Here I have couple of questions.
The structure is as follows.
{
_id:"127467812649871246",
"name":"Disha",
"last_name":"shukla",
"members":
[
{
name:"xyz"
},
{
name:"abc"
}
],
"user":"premium"
}
1] How to insert data in particular field when the data is already exists by referring the record ID ? In this case, insert a new member in "Members"
2] In some cases there wont be "user":"premium" field. Because I wont insert at first time. How do I check if that field is exists if I have inserted for some document ?
Any help will be appreciated :)
Thank you!

The $push command is used to insert data into an existing array in MongoDB. And $exists is used to check whether a field exists in a collection. Go to the links to find more.

1) You can use update by some selector, for example by name
CollectionName.update({name:"Disha"}, {$push: {members: {name: "new"}}})
2) If you want to check if the field exists use this
CollectionName.find({user: {$exists:true}}).
If you want to check if user is premium
CollectionName.find({user: "premium"}).
If you want to check both:
CollectionName.find({$and: [{user: {$exists:true}}, {user: "premium"}]})

Related

MongoDB creating index on a new field

I need to create a TTL Index in MongoDB and for that, I'm adding a new field "last_modified". I'm using the latest Python and pymongo in case this makes any difference.
After reading information on sparse and non-sparse indexes I understand that all documents that do not have "last_modified" will have this field added with the null value.
Is there a way to set some default value instead of null for those documents?
Alternatively, I'll have to update all documents in all DB instances using some migration function, but I would really like to do it clean...
Thanks in advance for any links or ideas!
I understand that all documents that do not have "last_modified" will have this field added with the null value.
No this is not true, sparse indexes just index documents where the field exists. documents without this field will just be out of the index converage.
Is there a way to set some default value instead of null for those documents? ... I'll have to update all documents in all DB instances ... to do it clean...
You have to run an update, there is no magic solution. Not sure why doing this is "not clean".
The update is super simple:
// this query will allow you to execute the update even if you started streaming new events with this field.
db.collection.updateMany({ last_modified: {$exists: false} }, { $set: { last_modified: defaultValue }})

Error while in update query in MongoDB

What I'm trying to achieve in here is to update a given set of documents that contain a given set of fields, either one, another or both.
I have two questions actually for this matter...
Can MongoDB process fields that aren't present in the document being processed? Like what I'm trying to achieve here, sum two fields, and if one is null just sum 0.
And the other one is the error that I'm getting in the query...
db.getCollection('my_collection').update({'$or': [{
'a_field': 1}, {
'another_field': 1
}
]},
{'$set': {
'another_field': {
'$sum': [
'$a_field', '$another_field'
]
}
},
'$unset': {'a_field': ''}})
Giving me the following error...
The dollar ($) prefixed field '$sum' in 'another_field.$sum' is not valid for storage.
There is no $sum UPDATE operator in mongodb and hence the error. The one you are confused with is an aggregation operator and can only be used to query data in a fashion.
Also, the operator you are looking at is $inc, however you CANNOT update the document in the fashion you are trying to. There is an OPEN ticket for this feature to mongodb. Ticket
Hope this clarifies
See this answer for more on achieving what you are trying to do.

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 to remove given list of documents from collection mongodb

how to Remove given list of documents from mongodb collection? eg:
i want to remove list of students which name containing empty value like.
var list=db.Student.find({'Name': {$eq: ''}})
db.Student.update($pull:{list})
but its is not working. is there any other best solution for this?
You can remove the documents with the given condition by passing a query document. Try this;
db.Student.remove( { Name : "" } )
You can refer this link for further clarifications.
http://docs.mongodb.org/manual/tutorial/remove-documents/
db.Student.remove({'Name':''})
Check the docs

Updating multiple documents in mongodb using _id field

I have sample products table and would like to update multiple documents using _id field. Every time, I try this it only updates the first doc in the $in clause I mentioned , not updating all.
db.products.update({_id:{$in:[ObjectId("507d95d5719dbef170f15bff"),
ObjectId("507d95d5719dbef170f15c01"), ObjectId("507d95d5719dbef170f15c00")]}},
{$set:{'monthly_price':7865}}, {multi:true})
You can first try running find on the products table to make sure that all the object ids actually exist.
You can also try explain command
give this a try:
db.<collection>.update( { query }, {$set: {monthly_price:7865}}, false, true)
I think the object id's which you have given doesn't exist in the collection.
I tried using the following query and it worked for me.
db.test.update({_id:{$in:[ObjectId("57b33483e5b9ce24f4910855"),
ObjectId("57b33483e5b9ce24f4910856"),
ObjectId("57b33489e5b9ce24f4910857"),
ObjectId("57b33491e5b9ce24f4910858")
]
}
},
{$set{'isCurrentStatus':true}},
{multi:true}
)