view of query in mongodb - mongodb

I have a collection ,this is one of it's docs :
{
"_id" : 1 ,
"first_name" : "john",
"phone" : [
{
"type" : "mobile",
"number" : "9151112233"
},
{
"type" : "home",
"city_code" : 51,
"number" : "55251544"
},
{
"type" : "mobile",
"number" : "9152425125"
}
]
}
I'm searching for "phones" that contain type "mobile" and show them.
I need something like this :
{
"number" : "9151112233",
"number" : "9152425125"
}
I write this query for that :
db.main.find({ _id : 1 , 'phone.type' : "mobile" },{'phone.number' : true , _id : false}).forEach(printjson)
I want to show only numbers that their types are mobile but this query show all to numbers because this single doc contain others too.
How can I fix it?

I'd use the aggregation framework along with the $unwind, $match and $project commands. This:
db.main.aggregate({$unwind:"$phone"},{$match:{"phone.type":"mobile"}},{$project:{"phone.number":1,"_id":0}})
produces this output:
{ "phone" : { "number" : "9151112233" } }
{ "phone" : { "number" : "9152425125" } }
which only matches the mobile numbers.
http://docs.mongodb.org/manual/aggregation/

Related

Updating two level sub-document which is list in mongoDB?

I have a hotel collection whose one of the document looks like this -
{
"_id" : "HOTEL_1",
"name" : "Decent hotel",
"chainId" : "CHN123",
"rooms" : [
{
"id" : "ROM1",
"name" : "decent rooms",
"ratePlans" : [
{
"ratePlanId" : "RPNB1191989873C2G",
"status" : "INACTIVE",
"marginPart" : {
"marginType" : "PERCENTAGE",
"margin" : "32"
}
},
{
"ratePlanId" : "RPNE0992HBG6I0GE8",
"status" : "INACTIVE",
"marginPart" : {
"marginType" : "PERCENTAGE",
"margin" : "32"
}
}
]
},
{
"id" : "ROM2",
"name" : "another decent rooms"
"ratePlans" : []
}
]
}
I need to update status as ACTIVE of all the rate plans of all the rooms with a certain condition like chainId.
I tried with this but failed -
db.hotel.updateMany({ "chainId" : "CHN_123"},{$set : {"rooms.$ratePlans.$status" : "ACTIVE" }});
I also want to update margin as common value say 50% to all such rates.
Instead of updateMany try the below query
db.hotel.update({ "chainId" : "CHN_123"},{$set : {"rooms.$ratePlans.$status" : "ACTIVE" }},{multi:true,upsert:false},function(err,doc){
console.log(doc)
});
It works always!!

how to match two fields in different lists in mongodb for update query

I need help please, I have to match two embedded document with their ids
for example my document structure is like this:
{
"id" : "00025",
"ean" : "01213134325",
"notify_stock" : NumberLong(10),
"specs" : [
{
"id" : "0005",
"spec" : [
{
"lang" : "fr-FR",
"text" : "taille"
}
],
"value" : [
{
"lang" : "fr-FR",
"text" : "grand"
}
]
}]
}
i have a file for multi language like this
sku_id;spec_id;spec_name;spec_value
00025;0005;size;big
00025;0006;color;black
so my query in mongodb is like this:
Modifier update query:
{
"skus.id" : "<string val>",
"skus.$.specs.id" : "<string val>"
}
Modifier update details:
{
"$push" : {
"skus.$.specs.$.spec" : {
"lang" : "<string val>",
"text" : "<string val>"
},
"skus.$.specs.$.value" : {
"lang" : "<string val>",
"text" : "<string val>"
}
}
}
when i execute this in Pentaho data integration with the step output mongodb, i got an error
"Too many positional (i.e. '$')
elements found in path 'skus.$.specs.$.spec'"

MongoDB aggregation and projection issue

helpful people of StackOverflow!
I'm in the process of learning how to work with MongoDB, and am currently stuck with one particular problem.
I'm building a guitar tabs app, working only with an "artist" base document. All other data are subdocuments. Depending on the accessed functionality (e.g: search, list tabs by artist, view single tab), I aggregate and project my documents accordingly.
However, I can't get one projection to work as I want.
Given the following data:
{
"artist" : "Jeff Buckley",
"songs" : [
{
"name" : "Grace",
"tabs" : [
{
"version" : 1,
"tab" : "...",
"tuning" : "DADGBe"
},
{
"version" : 2,
"tab" : "...",
"tuning" : "DADGBe"
}
]
},
{
"name" : "Last Goodbye",
"tabs" : [
{
"version" : 1,
"tab" : "...",
"tuning" : "DGDGBD"
},
{
"version" : 2,
"tab" : "...",
"tuning" : "EADGBe"
}
]
}
]
}
I want to aggregate it the following way for a list view:
{
"artist" : "Jeff Buckley",
"tabs" : [
{
"song" : "Grace",
"version" : 1
},
{
"song" : "Grace",
"version" : 2
},
{
"song" : "Last Goodbye",
"version" : 1
},
{
"song" : "Last Goodbye",
"version" : 2
},
]
}
I tried it with the following projection:
db.tabs.aggregate(
[
{
$project : {
artist : 1,
tabs.song : "$songs.name",
tabs.version : "$songs.tabs.version"
}
}
]
)
But instead I got:
{
"artist" : "Jeff Buckley",
"tabs" : {
"version" : [[2,1],[2,1]],
"song" : ["Grace","Last Goodbye"]
}
}
Can anyone point me in the right direction?
Thanks!
your aggregation query not correct $project only affect your json document keys
your aggretion query like this
db.tabs.aggregate(
{$unwind : "$songs"},
{$unwind : "$songs.tabs"},
{$group : {
_id:"$artist",
tabs:{$push : {song : "$songs.name",version:"$songs.tabs.version"}}}},
{$project : {
tabs:"$tabs",
artist:"$_id",
_id:0}}
).pretty()

MongoDB find substructure

I have a mongodb with a table named Patient. When I display the content with MongoVUE I see my Patients in this format:
/* 0 */
{
"_id" : ObjectId("547c4aa9dbe9665042dddf76"),
"Patient" : {
"Maidenname" : { },
"Phone" : {
"Type" : { },
"Number" : { }
},
"Citizenship" : { },
"SSN" : 1234567,
"Profession" : { },
"systemUID" : { },
"lid" : 111,
"system" : "abc",
"Address" : {
"Street" : { },
"State" : { },
"Zip" : { },
"Country" : { },
"City" : { }
},
"Lastname" : "asdf",
"Firstname" : "Test",
"Birthdate" : 19000101,
"Identifier" : {
"id" : 123,
"system" : "abc",
"UID" : { }
}
}
}
I would like to make a find on the field Firstname with value Test, this is my query:
db.Patient.find({Firstname:"Test"})
But it returns 0 rows.
I also tried this one:
db.Patient.find({Patient : {Firstname:"Test"}})
Also 0 rows returned.
When I do a find like this:
db.Patient.find()
I get all data. (also the one with "Firstname" : "Test")
Can anyone help me with that find query?
Should try this it work well
db.patiens.find({"Patient.Firstname":"Test"})
Since Firstname is in Patient object, it is its property you need to select is as
db.Patient.find({"Patient.Firstname":"Test"})

how to use aggregation of mongodb

From the data as given below, I want to sum all Values fields.
Please let me know how can I do it using aggregation functionality of mongodb.
{"MetricRecord":
{ "SchemaVersion" : "0.12",
"Product": {
"ProductName" : "abc",
"ProductVersion": "7.5.0.1" ,
"ProductId" : "1234567890ABDFGH12345",
"InstanceId" : "12345BA32",
"InstanceName" : "1234SS123",
"SystemId" : "somehost.com"
},
"Tenant" : {
"CustomerId" : "222-555-124",
"ServiceCode": "xyzxyzxyz12345yyy"
},
"Metrics" : [
{
"ReportType" :[
{ "report" : "billing" },
],
"LogTime" : "2013-12-08T12:34:56:01Z" ,
"Type" : "AuthorizedUsers",
"SubType" : "registered",
"Value" : "125",
"UnitOfMeasure": "USD",
"Period" : {
"StartTime" : "2013-12-07T00:00:00:01Z",
"EndTime" : "2013-12-08T00:00:00:01Z"
}
},
{
"ReportType" :[
{ "report" : "billing" }
],
"LogTime" : "2013-12-08T12:34:56:01Z" ,
"Type" : "NumberOfTickets",
"SubType" : "resolved",
"Value" : "430",
"UnitOfMeasure": "USD",
"Period" : {
"StartTime" : "2013-12-07T00:00:00:01Z",
"EndTime" : "2013-12-08T00:00:00:01Z"
}
}
]
}
}
So, results which I expect from summation of values is 430+125 i.e. 555
Your document contains string value for MetricRecord.Metrics[index].Value field and i am not sure why are you trying to sum up the string values. if it is a typo and your document contains numerical values for MetricRecord.Metrics[index].Value field then you can try the following query
db.metrics.aggregate([
{$unwind:"$MetricRecord.Metrics"},
{$group:{_id:"$_id",sum:{$sum:"$MetricRecord.Metrics.Value"}}}
])
In the above document posted, if your value field is like
MetricRecord.Metrics[0].Value is 125(not "125")
MetricRecord.Metrics[1].Value is 430(not "430")
you will get the following output
{
"result" : [
{
"_id" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
"sum" : 555
}
],
"ok" : 1
}
The above sample query is composed assuming you have the default mongodb "_id" field and you are using a metrics collection. You have to manipulate the query as per you requirements.