Mongodb update with $concat and field missing - mongodb

I wanted to update a collection to set a new Field with other inner field
it looks like to generate a person's full name .
MongoDB Enterprise > db.name.find()
{ "_id" : ObjectId("5d7ca743c45316e35251a49e"), "first" : "Don", "middle" : "Jhon", "last" : "Trump" }
{ "_id" : ObjectId("5d7ca75bc45316e35251a49f"), "first" : "Dila", "last" : "Tp" }
{ "_id" : ObjectId("5d7ca76dc45316e35251a4a0"), "first" : "Li", "last" : "Wei" }
I want to set the full name with $first +$middle + $last in One
update
I try to use update with an aggregation pipeline. this is a new feature in mongodb 4.2
db.name.updateMany({},[{$set:{full:{$concat: [ "$first", "$middle","$last" ] }}}])
but this result return a lot of null value when some field is missing .
db.name.find()
{ "_id" : ObjectId("5d7ca743c45316e35251a49e"), "first" : "Don", "middle" : "Jhon", "last" : "Trump", "full" : "DonJhonTrump" }
{ "_id" : ObjectId("5d7ca75bc45316e35251a49f"), "first" : "Dila", "last" : "Tp", "full" : null }
{ "_id" : ObjectId("5d7ca76dc45316e35251a4a0"), "first" : "Li", "last" : "Wei", "full" : null }

What you are looking for is ifNull function. Rewrite your query like this
db.name.updateMany({},[{$set:{full:{$concat: [ {$ifNull:["$first", ""]}, {$ifNull:["$middle", ""]},{$ifNull:["$last", ""]} ] }}}])

I also try use with $cond it also worked but more complicated
db.name.updateMany({},[{$set:{full:{$concat: [ "$first", {"$cond" :{if :{$gt:["$middle", null]},then :"$middle" ,else :""}},"$last" ] }}}])
put it here to help others if needed .

Related

MongoDB count occurances of a substring in a collection

Hello I'm a MongoDb beginner. I have a database of a IRC chatlog. The document structure is very simple
{
"_id" : ObjectId("000"),
"user" : "username",
"message" : "foobar foobar potato idontknow",
"time" : NumberLong(1451775601469)
}
I have thousands of these and I want to count the number of occurrences of the string "foobar". I have googled this issue and found something about aggregations. I looks very complicated and I haven't really found any issue this "simple". I'd be glad if someone pointed me in the right direction what to research and I wouldn't mind an example command that does exactly this what I want. Thank you.
There is no any built-in operator to solve your request.
You can try this query, but it has very poor performance:
db.chat.find().forEach(function(doc){
print(doc["user"] + " > " + ((doc["message"].match(/foobar/g) || []).length))
})
If you could change your message field to array, then we could apply aggregation...
EDIT:
If you add array of splitted words into your entry, we can apply aggregation
Sample:
{
"_id" : ObjectId("569bb7040586bcb40f7d2539"),
"user" : "username",
"fullmessage" : "foobar foobar potato idontknow",
"message" : [
"foobar",
"foobar",
"potato",
"idontknow"
],
"time" : NumberLong(1451775601469)
}
Aggregation. We create new entry for each array element, match given word (foobar, in this case) and then count matched result.
db.chat.aggregate([
{"$unwind" : "$message"},
{"$match" : {"message" : {"$regex" : "foobar", "$options" : "i"}}},
{"$group" : {_id:{"_id" : "$_id", "user" : "$user", "time" : "$time", "fullmessage" : "$fullmessage"}, "count" : {$sum:1}}},
{"$project" : {_id:"$_id._id", "user" : "$_id.user", "time" : "$_id.time", "fullmessage" : "$_id.fullmessage", "count" : "$count"}}
])
Result:
[
{
"_id" : ObjectId("569bb7040586bcb40f7d2539"),
"count" : 2,
"user" : "username",
"time" : NumberLong(1451775601469),
"fullmessage" : "foobar foobar potato idontknow"
}
]

How to query an array of objects in mongodb

I have an object structure as shown below
{
"_id" : ObjectId("55d164f1c8f2c53a82535b9a"),
"plant_name" : "TOTAL",
"installed_capacity" : 3473,
"wind_data" : [
{
"date" : "16-08-15",
"timestamp" : " 16:27:15",
"generated_capacity" : 617.24,
"frequency" : 50.01
},
{
"date" : "16-08-15",
"timestamp" : " 21:21:15",
"generated_capacity" : 670.25,
"frequency" : 49.94
}, ....]
}
I need to sum up (at least retrieve) "generated_capacity" of all the objects under "wind_data" having "date" equal to "16-08-15" of "TOTAL" object. I have tried this query
db.collectionName.aggregate(
{"$unwind":"$wind_data"},
{"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}}
)
But, this query is not working. Please suggest some way to figure this out.
The following query would do the job
db.collectionName.aggregate([
{"$unwind":"$wind_data"},
{"$match":{"plant_name":"TOTAL","wind_data.date":"16-08-15"}},
{"$group":{"_id":"$wind_data.date","generated_capacity_sum":{"$sum":"$wind_data.generated_capacity"}}}
])

Get specific object in array of array in MongoDB

I need get a specific object in array of array in MongoDB.
I need get only the task object = [_id = ObjectId("543429a2cb38b1d83c3ff2c2")].
My document (projects):
{
"_id" : ObjectId("543428c2cb38b1d83c3ff2bd"),
"name" : "new project",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"members" : [
ObjectId("5424ac37eb0ea85d4c921f8b")
],
"US" : [
{
"_id" : ObjectId("5434297fcb38b1d83c3ff2c0"),
"name" : "Test Story",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"tasks" : [
{
"_id" : ObjectId("54342987cb38b1d83c3ff2c1"),
"name" : "teste3",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
},
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
]
}
]
}
Result expected:
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
But i not getting it.
I still testing with no success:
db.projects.find({
"US.tasks._id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}, { "US.tasks.$" : 1 })
I tryed with $elemMatch too, but return nothing.
db.projects.find({
"US" : {
"tasks" : {
$elemMatch : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}
}
}
})
Can i get ONLY my result expected using find()? If not, what and how use?
Thanks!
You will need an aggregation for that:
db.projects.aggregate([{$unwind:"$US"},
{$unwind:"$US.tasks"},
{$match:{"US.tasks._id":ObjectId("543429a2cb38b1d83c3ff2c2")}},
{$project:{_id:0,"task":"$US.tasks"}}])
should return
{ task : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
Explanation:
$unwind creates a new (virtual) document for each array element
$match is the query part of your find
$project is similar as to project part in find i.e. it specifies the fields you want to get in the results
You might want to add a second $match before the $unwind if you know the document you are searching (look at performance metrics).
Edit: added a second $unwind since US is an array.
Don't know what you are doing (so realy can't tell and just sugesting) but you might want to examine if your schema (and mongodb) is ideal for your task because the document looks just like denormalized relational data probably a relational database would be better for you.

Mongodb + Mongoose: trying to add a sub-sub-item

Does this makes any sense when trying to add a sub-sub-item? (I'm new to mongo - be merciful :-))
question = db.questions.findOne({_id: ObjectId("529c5d44211c9a8c11000006")})
question.answers[0].votes.insert(...)
When I run this from the mongo console the result is an error saying [object object] does not have the method insert.
I have the following mongoDB Question Schema.
{
"__v" : 2,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d44211c9a8c11000006"),
"answers" : [
{
"postDate" : ISODate("2013-12-02T10:14:19.060Z"),
"postDateText" : "15min ago",
"authorEmail" : "guys#pix.com",
"authorName" : "guys#pix.com",
"body" : "You need magic powder",
"isWinner" : false,
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d7b211c9a8c11000008"),
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
],
"authorEmail" : "guys#wix.com",
"authorName" : "guys#wix.com",
"body" : "I'm trying to fly...\n\n<pre class=\"brush: js;\">\nfunction logName(name) {\n console.log(name);\n}\n</pre>",
"isResolved" : false,
"postDate" : ISODate("2013-12-02T10:13:24.235Z"),
"tags" : [
"fly"
],
"title" : "How do I fly?",
"views" : [],
"votes" : [
{
"voteType" : "up",
"_creator" : ObjectId("529c5d2d211c9a8c11000005"),
"_id" : ObjectId("529c5d5b211c9a8c11000007")
}
]
}
I'm trying, given a questionId and an answerId to add a vote to the votes array (which is inside the answer). I can't seem to do it. Help?
insert is for adding whole new documents; when you just want to add a new element to an array field of an existing document, you can use update along with an operator like $push.
So, in the shell you would use something like this:
db.questions.update(
{_id: ObjectId("529c5d44211c9a8c11000006")},
{'answers.0.votes': {$push: voteToPush}})

mongodb change $group output format

I have the following document structure
{
"timestamp" : 13512493603565120,<br>
"value" : 1,<br>
"y" : 42,<br>
"M" : 513,<br>
"w" : 2234,<br>
"d" : 15639,<br>
"S" : 46918,<br>
"h" : 375347,<br>
"m" : 22520822,<br>
"s" : 1351249360,<br>
"_id" : ObjectId("508aa61100b5457c04000001"),<br>
"__v" : 0<br>
}
I have a mongodb aggregate as follows to sum up values grouping by field y:
aggregate({
$group : {_id : "$y", value:{$sum:4}}
})
This will give me
[
{
"_id": 42,
"value": 16
}
]
What I want now is to format this output so that it looks like this:
[
[13512493603565100, 2],
[13512493605167900, 1]
]
ie:
[
[<timestamp>,<sum of value grouped by field y>],
[<timestamp>,<sum of value grouped by field y>]
]
I looked at $project but I still cant figure out how I can use it to get the desired output
Not possible as of now apparently (using mapreduce or aggregate).
Hope this will be added soon.