mongodb already exists array added another value query - mongodb

I have notification click table like this:
{
"_id" : ObjectId("5d00d4e1d720cc4cb1b24566"),
"createdOn" : ISODate("2019-06-12T10:33:05.866Z"),
"notification_center_id" : [
ObjectId("5c59343523f05e2ff13938d6")
],
"user_id" : ObjectId("5bc5dc03f6d24d29077dd362"),
"__v" : 0
}
I want to check if user_id "5bc5dc03f6d24d29077dd362" is already exists then added another notification_center_id in already exists record.
like this
{
"_id" : ObjectId("5d00d4e1d720cc4cb1b24566"),
"createdOn" : ISODate("2019-06-12T10:33:05.866Z"),
"notification_center_id" : [
ObjectId("5c59343523f05e2ff13938d6"),
ObjectId("5c5c4610c6d91403f38eda52")
],
"user_id" : ObjectId("5bc5dc03f6d24d29077dd362"),
"__v" : 0
}
I want query that first check user id exists if exists then added another notification record in notification_center_id field.
If user is not exists then I want add another record in collection
one more condition here, if notification_center_id is not inserted duplicate. if it's exist then not added.
Please help me.

db.getCollection('test').update(
{"user_id" : ObjectId("5bc5dc03f6d24d29077dd362")},
{"$push" : {"notification_center_id" : new ObjectId()}}
)
In your question, you have not mentioned what to do if user_id doesn't exist. So doing nothing in that case.
After your comment
db.getCollection('test').update(
{"user_id" : ObjectId("5c59343523f05e2ff13938d6")},
{
"$push" : {"notification_center_id" : new ObjectId()},
"$setOnInsert" : {"createdOn" : new ISODate(), "__v" : 0}
},
{"upsert" : true}
)

$addToSet update operator is used to append an element to an array and preserves uniqueness of values into an array.
db.notifications.update({"_id" : ObjectId("5d00d4e1d720cc4cb1b24566")}
, { $addToSet: { notification_center_id: new ObjectId() } })

Related

how to use update query in mongoDb?

I have few documents in user Collection like below .I need to update ancestors field alone,Need to add few more values.
db.users.find()
{
"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc"),
"DOB" : ISODate("1979-05-23T00:00:00Z"),
"userImage" : "sathish_1589780950636.jpeg",
"createdDateTime" : ISODate("2016-02-01T09:43:27Z"),
"modifiedDateTime" : ISODate("2017-04-26T15:57:09Z"),
"status" : "active",
"ancestors" : [
ObjectId("5d9fd81b3d598088d2ea5dc7")
],
"parent" : ObjectId("5d9fd81b3d598088d2ea5dc7")
}
When i tried the below query.
db.users.update({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},{$set:{"ancestors" : [
ObjectId("5f45f9491ff4bd74ec754e3a"),
ObjectId("5d9fd8203d598088d2ea5dcd"),
ObjectId("5d9fd8723d598088d2ea5e43")
]}})
It just replace the old one and completely adding the new one.
I need the result to be like this .old data should also remain and new one should be added.
"ancestors" : [
ObjectId("5f45f9491ff4bd74ec754e3a"),
ObjectId("5d9fd8203d598088d2ea5dcd"),
ObjectId("5d9fd81b3d598088d2ea5dc7"),
ObjectId("5d9fd8723d598088d2ea5e43")
]
This update query should be done in all documents in that collection. the above mentioned 3 values to be added in all documents, instead of find and update, I should be doing bulk updated
I think you can run the following:
db.users.updateOne({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},{$addToSet:{"ancestors" :{ $each: [
ObjectId("5f45f9491ff4bd74ec754e3a"),
ObjectId("5d9fd8203d598088d2ea5dcd"),
ObjectId("5d9fd8723d598088d2ea5e43")
]}}})
ref: https://docs.mongodb.com/manual/reference/operator/update/each/
You can use mongodb method $push
db.users.update({"_id" : ObjectId("5d9fd81f3d598088d2ea5dcc")},
{ $push: {ancestors:ObjectId("5f45f9491ff4bd74ec754e3a") } })
[check doc][1]
[1]: https://docs.mongodb.com/manual/reference/operator/update/push/

What are the efficient query for mongodb if value exist on array then don't update and return the error that id already exist

I have an entry stored on my collection like this:
{
"_id" : ObjectId("5d416c595f19962ff0680dbc"),
"data" : {
"a" : 6,
"b" : [
"5c35f04c4e92b8337885d9a6"
]
},
"image" : "123.jpg",
"hyperlinks" : "google.com",
"expirydate" : ISODate("2019-08-27T06:10:35.074Z"),
"createdate" : ISODate("2019-07-31T10:24:25.311Z"),
"lastmodified" : ISODate("2019-07-31T10:24:25.311Z"),
"__v" : 0
},
{
"_id" : ObjectId("5d416c595f19962ff0680dbd"),
"data" : {
"a" : 90,
"b" : [
"5c35f04c4e92b8337885d9a7"
]
},
"image" : "456.jpg",
"hyperlinks" : "google.com",
"expirydate" : ISODate("2019-08-27T06:10:35.074Z"),
"createdate" : ISODate("2019-07-31T10:24:25.311Z"),
"lastmodified" : ISODate("2019-07-31T10:24:25.311Z"),
"__v" : 0
}
I have to write the query for push userid on b array which is under data object and increment the a counter which is also under data object.
For that, I wrote the Code i.e
db.collection.updateOne({_id: ObjectId("5d416c595f19962ff0680dbd")},
{$inc: {'data.a': 1}, $push: {'data.b': '124sdff54f5s4fg5'}}
)
I also want to check that if that id exist on array then return the response that following id exist, so for that I wrote extra query which will check and if id exist then return the error response that following id exist,
My question is that any single query will do this? Like I don't want to write Two Queries for single task.
Any help is really appreciated for that
You can add one more check in the update query on "data.b". Following would be the query:
db.collection.updateOne(
{
_id: ObjectId("5d416c595f19962ff0680dbd"),
"data.b":{
$ne: "124sdff54f5s4fg5"
}
},
{
$inc: {'data.a': 1},
$push: {'data.b': '124sdff54f5s4fg5'}
}
)
For duplicate entry, you would get the following response:
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
If matched count is 0, you can show the error that the id already exists.
You can use the operator $addToSet to check if the element already exits in the array.
db.collection.updateOne({_id: ObjectId("5d416c595f19962ff0680dbd")},
{$inc: {'data.a': 1}, $addToSet: {'data.b': '124sdff54f5s4fg5'}}
)

MongoDB - update an existing document in a collection

I have a collection called user_roles and it contains a field called rights which is an array of strings.
I want to update a document within user_roles collection that has _id = 5b1509f8b95b4bfe2b638508 by appending a new string element into the rights field.
So basically, after this update collection should hold the additional element "ui.dealers.measures.retrieve" as shown below.
{
"_id" : ObjectId("5b1509f8b95b4bfe2b638508"),
"type" : "coach",
"name" : "Coach",
"flavours" : {
"coach" : NumberInt(1)
},
"rights" : [
"ui.dealers.retrieve",
"ui.dealers.dossier.retrieve",
"ui.dealers.dossier.update",
"ui.dealers.documents.retrieve",
"ui.dealers.documents.create",
"ui.dealers.documents.delete",
"ui.dealers.events.retrieve",
"ui.dealers.events.create",
"ui.dealers.events.update",
"ui.dealers.events.export",
"ui.dealers.events.delete",
"ui.dealers.kpis.retrieve",
"ui.dealers.kpis.update",
"ui.dealers.blueprints.retrieve",
"ui.dealers.blueprints.create",
"ui.dealers.gap.retrieve",
"ui.dealers.gap.update",
"ui.dealers.measures.create",
"ui.dealers.surveys.retrieve",
"ui.dealers.surveys.update",
"ui.dealers.measures.retrieve"
],
"createdAt" : ISODate("2018-06-04T09:44:24.394+0000"),
"updatedAt" : ISODate("2018-06-04T10:01:56.428+0000")
}
Please try this
db.collection.update({_id:ObjectId("5b1509f8b95b4bfe2b638508")},{
$push:{
"rights":"ui.dealers.measures.retrieve"
}
})

Update nested object based on "name" field

I'm new in MongoDB, so forgive my ignorance.Suppose you have the document:
{ "_id" : ObjectId("..."),
"google" : { "googleId" : ..., "username" : "Johnny",
"followers" : [ { name:"niklas", email:"niklas#hotmail.com" } ] },
"__v" : 0 }
When admin "Johny" obtains a new follower, i can add him using
User.update(query,
{$addToSet:{google.followers:{name:"Maria" , email:"Maria#hotmail.com"}}},
{upsert:true,new:true}...
My problem occurs when "niklas" changes his email. Using $addToSet simply adds a new object. How can i update the existing email of "niklas" or add it if there is no such entry;
Thanks in advance
To update existing email of "niklas", you can the positional "$" operator. Something like:
db.User.update(
{"followers.name" : "niklasaa"},
{$set: {"followers.$.email": "new-email"}}
)

Unique key in moongose db

I have the following DB:
{
"_id" : ObjectId("556da79a77f9f7465943ff93"),
"guid" : "a12345",
"update_day" : "12:05:10 02.06.15"
}
{
"_id" : ObjectId("556dc4509a0a6a002f97e972"),
"guid" : "bbbb",
"update_day" : "15:03:10 02.06.15"
"__v" : 0
}
{
"_id" : ObjectId("556dc470e57836242f5519eb"),
"guid" : "bbbb",
"update_day" : "15:03:10 02.06.15"
"__v" : 0
}
{
"_id" : ObjectId("556dc47c7e882d3c2fe9e0fd"),
"guid" : "bbbb",
"update_day" : "15:03:10 02.06.15"
"__v" : 0
}
I want to set the guid to be unique, so no to duplicate is possible (Like primary key in MYSQL). So the DB will look like this:
{
"_id" : ObjectId("556da79a77f9f7465943ff93"),
"guid" : "a12345",
"update_day" : "12:05:10 02.06.15"
}
{
"_id" : ObjectId("556dc4509a0a6a002f97e972"),
"guid" : "bbbb",
"update_day" : "15:03:10 02.06.15"
"__v" : 0
}
and when I will insert another "guid":"bbbb" (with the save command), it will fails.
While declaring schema in mongoose, do this
guid : { type : String, unique : true}
AND if you want mongodb to create the guid on its own (like _id) then do this
guid : { type : String, index : { unique : true} }
First, you have to deal with the current state of your MongoDB collection and delete all the duplicated documents.
One thing is sure : you won't be able to create the unique index with duplicates in your collection and dropDupes is now deprecated since the version 2.7.5 so you can't use it. By the way, it was removed because it was almost impossible to predict which document would be deleted in the process.
Two possible solutions :
Create a new collection. Create the unique index on this new collection and run a batch to copy all the documents from the old collection to the new one and make sure you ignore duplicated key error during the process.
Deal with it in your own collection manually :
make sure you won't insert more duplicated documents in your code,
run a batch on your collection to delete the duplicates (and make sure you keep the good one if they are not completely identical),
then add the unique index.
I would declare my guid like so in mongoose :
guid : { type : String, unique : true}