insert and update a field in MongoDB - mongodb

I want to update all the collection field profile.email with emails.[0].address just something like this in SQL:
update dbo.users
set profile.email=emials.[0].address
I know this stupid code won't work on SQL either. Just put it to make it sensible for what I need.
it is something like this,but is not working:
db.getCollection('users').update(
{_id: "QYoHQkTuTXnEC6Pws"},
{$set:
{'profile.email': db.getCollection('users').aggregate({$match: {_id:'QYoHQkTuTXnEC6Pws'}},
{$project: {_id:0,email: {$arrayElemAt:
['$emails.address',0]}}})
}
}
)
the result is not true :
"email" : {
"_batch" : [
{
"email" : "deleted_sadaf#ham.com"
}
],
"_useReadCommands" : true,
"_cursorid" : NumberLong(0),
"_batchSize" : undefined,
"_ns" : "meteor.users",
"_db" : {
"_mongo" : {
"slaveOk" : true,
"host" : "localhost:3001",
"defaultDB" : "",
"_readMode" : "commands",
"_writeMode" : "commands"
},
"_name" : "meteor"
},
"_collName" : "users",
"_cursorHandle" : {}
}

You have to iterate over each document and update to achieve expected result.
db.users.find({}).forEach(function (user) {
db.users.update({_id: user._id}, {$set: {'profile.email': user.emails[0].address}});
});

db.users.update({_id: "doc id"},
{$set: {'profile.email': db.users.find({_id: "doc id"}).emails[0].address}
})
Your task has 2 steps:
1. get the email address, which is performed by "db.users.find"
2. update the document, which is performed by "db.users.update"

Related

How to update Meteor array element inside a document

I have a Meteor Mongo document as shown below
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "b1#gmail.com",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I want to update a specific array element's email with custom generated id using Meteor query something like the below.
for instance, I want to update the document
if 'users.id' == "b1#gmail.com" then update it to users.id = 'SomeIDXXX'
So updated document should looks like below.
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "SomeIDXXX",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I have tried the below but didnt work.
Divisions.update(
{ activityId: activityId, "users.id": emailId },
{ $set: { "users": { id: _id } } }
);
Can someone help me with the relevant Meteor query ? Thanks !
Your query is actually almost right except for a small part where we want to identify the element to be updated by its index.
Divisions.update({
"activityId": "aRDABihAYFoAW7jbC",
"users.id": "b1#gmail.com"
}, {
$set: {"users.$.id": "b2#gmail.com"}
})
You might need the arrayFilters option.
Divisions.update(
{ activityId: activityId },
{ $set: { "users.$[elem].id": "SomeIDXXX" } },
{ arrayFilters: [ { "elem.id": "b1#gmail.com" } ], multi: true }
);
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
You need to use the $push operator instead of $set.
{ $push: { <field1>: <value1>, ... } }

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 latest subdocument

here is my mongo document..
{
"_id" : ObjectId("5a69d0acb76d1c2e08e4ccd8"),
"subscriptions" : [
{
"sub_id" : "5a56fd399dd78e33948c9b8e",
"invoice_id" : "5a56fd399dd78e33948c9b8d"
},
{
"sub_id" : "5a56fd399dd78e33948c9b8e"
}
]
}
i want to update and upsert invoice_id into last element of sub-array..
i have tried..
sort: {$natural: -1},
subscription.$.invoice
what i want it to be is....
{
"_id" : ObjectId("5a69d0acb76d1c2e08e4ccd8"),
"subscriptions" : [
{
"sub_id" : "5a56fd399dd78e33948c9b8e",
"invoice_id" : "5a56fd399dd78e33948c9b8d"
},
{
"sub_id" : "5a56fd399dd78e33948c9b8e",
"invoice_id" : "5a56fd399dd78e33948c9b8f"
}
]
}
While there are ways to get the last array element, like Saravana shows in her answer, I don't recommend doing it that way because it introduces race conditions. For example, if two subs are added simultaneously, you can't depend on which one is 'last' in the array.
If an invoice_id has to be tied to a specific sub_id, then it's far better to query and find that specific element in the array, then add the invoice_id to it.
In the comments, the OP indicated that the current order of operations is 1) add sub_id, 2) insert the invoice record into the INVOICE collection and get the invoice_id, 3) add the invoice_id into the new subscription.
However, if you already have the sub_id, then it's better to re-order your operations this way: 1) insert the invoice record and get the invoice_id 2) add both sub_id and invoice_id with a single operation.
Doing this improves performance (eliminates the second update operation), but more importantly, eliminates race conditions because you're adding both sub_id and invoice_id at the same time.
we can get the document and update last element by index
> var doc = db.sub.findOne({"_id" : ObjectId("5a69d0acb76d1c2e08e4ccd8")})
> if ( doc.subscriptions.length - 1 >= 0 )
doc.subscriptions[doc.subscriptions.length-1].invoice_id="5a56fd399dd78e33948c9b8f"
> db.sub.update({_id:doc._id},doc)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
or write an aggregation pipeline to form the document and use it for update
db.sub.aggregate(
[
{$match : { "_id" : ObjectId("5a69d0acb76d1c2e08e4ccd8") }},
{$addFields : { last : { $subtract : [{$size : "$subscriptions"},1]}}},
{$unwind : { path :"$subscriptions" , includeArrayIndex : "idx"}},
{$project : { "subscriptions.sub_id" : 1,
"subscriptions.invoice_id" : {
$cond : {
if: { $eq: [ "$idx", "$last" ] },
then: "5a56fd399dd78e33948c9b8f",
else: "$$REMOVE"
}
}
}
},
{$group : {_id : "$_id", subscriptions : {$push : "$subscriptions"}}}
]
).pretty()
result doc
{
"_id" : ObjectId("5a69d0acb76d1c2e08e4ccd8"),
"subscriptions" : [
{
"sub_id" : "5a56fd399dd78e33948c9b8e"
},
{
"sub_id" : "5a56fd399dd78e33948c9b8e",
"invoice_id" : "5a56fd399dd78e33948c9b8f"
}
]
}

How to set keys in mongoDB aggregation?

The idea is to go from a collection of documents like this:
{
"_id" : ObjectId("58ff4fa372ac97344d5672c2"),
"direction" : 1,
"post" : ObjectId("58ff4ea572ac97344d5672c1"),
"user" : ObjectId("586b84239ae9590ab66bd3ad")
}
{
"_id" : ObjectId("58ff4c9f2952d7341d4afc0c"),
"direction" : -1,
"post" : ObjectId("58fc15a3fb3bed0fd54bfd95"),
"user" : ObjectId("586b84239ae9590ab66bd3ad")
}
To this:
[
//post: direction
"58ff4ea572ac97344d5672c1": 1,
"58fc15a3fb3bed0fd54bfd95": -1
]
I can't seem to find anything in the MongoDB Aggregation docs that allows you to set the key name using the value of another field.
I'm expecting this code to work, but I can see why it doesn't. It thinks that "$post" refers to a MongoDB expression.
db.votes.aggregate([
{$group: {
_id: null,
entries: {
$addToSet: {
"$post": "$direction"
}
}
}}
])

Minimongo nested query embed documents

i want to search into an embed document in mongodb and return only what i'm looking for.
Here's the document:
"_id" : "yH8HmCPz6H6E8Hinq",
"between" : [
"4bgdLrztpqgwAkZP4",
"9jZhXHjAkoY7mmX7B"
],
"messages" : [
{
"content" : "fdsqf",
"user" : "4bgdLrztpqgwAkZP4",
"created_at" : ISODate("2016-11-17T23:13:59.659Z"),
"isSeen" : false,
"sender" : "John doe",
"receiver" : "Elen doe"
},
{
"content" : "test",
"user" : "9jZhXHjAkoY7mmX7B",
"created_at" : ISODate("2016-11-20T11:42:42.893Z"),
"isSeen" : false,
"sender" : "Elen doe",
"receiver" : "John doe"
}
]
All what i want to have is "messages.isSeen" equals to false and receiver isn't Meteor.user().username.
And finally how to update that field to become true.
Hope someone can help ! Thanks in advance !
You need to include the _id in the query and $set in the update.
let id = "yH8HmCPz6H6E8Hinq";
let username = Meteor.user().username;
let query = { _id: id, messages: { $elemMatch: { isSeen: false, receiver: { $ne: username }}}};
Chat.update(query,{ $set: { "messages.$.isSeen": true }});
You need something like:
Chat.update({
'messages.isSeen': false, // isSeen is false
'messages.receiver': { // Receiver is
$ne: Meteor.user().username // not equal to Meteor.user().username
}
}, {
'messages.$isSeen': true // Set isSeen to true
});