how to query sub document in mongodb? - mongodb

how to query the sub document in sub document.?
how to retreive the name of the city in commercial document.
{
"_id" : " c2 ",
"commercial" : {
" type " : " restaurant ",
" sale_type " : " sale ",
" owner_name " : " josi schmit",
" address " : {
" street " : " kleine rittergasse ",
" plot_no " : 4,
" city " : " frankfurt ",
" state " : " hessen ",
" country " : "germany ",
"postal_code " : 60329,
"email" : " josi123#gmail.com"
},
" total_area " : " 300 sq meters ",
" sale_price(EUR) " : 100000,
" features " : {
" lifts " : 1,
" heating " : true,
" parking " : true,
" kitchen " : true,
" security_cameras " : true,
" furniture " : true
}
}
}
here is my query but i knew i'm wrong please help me.
db.property.find( {"_id": "c2" , "address.city": "c2"})
Regards
Sreekanth

Actualy there are two methods to do that:
db.property.find ( { "_id": "c2", "commercial.address.city": "c2" }, {"commercial.address.city": true} )
db.property.find ( { "_id": "c2", "commercial": { "address" : { "city": "c2" }}} )
The difference in both cases is that in first case mongo will follow the index if you have an index commercial.address.city, the second one will not, so I sugest you use the first one

Related

Aggregation for counting the occurrence of sub-string in main string in mongodb

I am new to MongoDB and might be its a noob question.
I want to count the number of times "lupoK" repeated in the message field which is - "message" : "first lupoK lupoK" using aggregation in MongoDB, I am using studio3t interface.
My document structure is -
{
"_id" : ObjectId("5df9c780b05196da93be262b"),
"id" : "61a4c53a-aa99-4336-ab4f-07bb7f618889",
"time" : "00:00:45",
"username" : "siul",
"message" : "***first lupoK lupoK***",
"emoticon_place" : [
{
"_id" : "128428",
"begin" : NumberInt(6),
"end" : NumberInt(10)
}
],
"fragments" : [
{
"text" : "first "
},
{
"emoticon" : {
"emoticon_id" : "128428",
"emoticon_set_id" : ""
},
"text" : "***lupoK***"
},
{
"emoticon" : {
"emoticon_id" : "128428",
"emoticon_set_id" : ""
},
"text" : "***lupoK***"
}
]
}
Thanks in advance!!!
This works in mongo shell (assuming the message field is a string and exists):
db.test.aggregate( [
{
$project: {
_id: 0,
message: 1,
count: {
$subtract: [
{ $size: { $split: [ "$message", "lupoK" ] } }, 1
]
}
}
}
] )
NOTES:
The $split operation splits the message string based on a delimiter - in this case the delimiter is "lupoK". The split returns an array of tokens which are separated by "lupoK". So, the number of tokens minus 1, gives the number of times "lupoK" is used, the count of occurrence of "lupoK".
Check the result with these sample message strings:
"***first lupoK lupoK***"
"lupoKlupoK"
" lupoK lupoK "
""
"lupoKlupoKlupoK"
"lupoK"
"HELLO * lupoK* WORLD"
"HELLO WORLD"
"***first lupoK lupoKlupoK lupoK***lupoK *** last lupoK."
For example, the tokens for some strings:
"***first lupoK lupoK***" generates these three tokens : [ "***first", " ", "***" ]
"HELLO * lupoK* WORLD" has these two tokens: [ "HELLO * ", "* WORLD" ]
"***first lupoK lupoKlupoK lupoK***lupoK *** last lupoK." has seven tokens: [ "***first ", " ", "", " ", "***", " ***last ", "." ]

How to print nested array using mongo query

I'm trying to print the values of an nested array.But getting execute script error.How do I print object BSON and avoid error in for nested array.
Note : I want to do with print and not find().
Customer schema
{
"name" : "Sam",
"phone" : [
{
"home" : "123456",
"work" : "045842"
}]}
query
db.getCollection('customer').find({}).forEach( function(cust)
{
print("Customer Name : " + cust.name); // prints Sam
print("Home Contact : " + cust.phone) // prints [object BSON]
print("Home Contact : " + cust.phone.home) // throws error
});
You could use aggregation if there are multiple items in the array
db.collectionName.aggregate([
{ $unwind: { path: "$phone", preserveNullAndEmptyArrays: true}},
]).forEach(function(doc){
print(doc.name)
if(doc.phone !== undefined) print(doc.phone.home)
if(doc.phone !== undefined) print(doc.phone.work)
})
You just need to convert the object to string and access the array;
print("Home Contact : " + JSON.stringify(cust.phone[0]))
// prints ` Home Contact: { "home" : "123456", "work" : "045842" }
print("Home Contact : " + cust.phone[0].home) // "123456"
An example:
aireclaimRs:PRIMARY> use test
switched to db test
aireclaimRs:PRIMARY> db.createCollection('customer')
{ "ok" : 1 }
aireclaimRs:PRIMARY> db.customer.insert( {
... "name" : "Sam",
... "phone" : [
... {
... "home" : "123456",
... "work" : "045842"
... }]})
WriteResult({ "nInserted" : 1 })
aireclaimRs:PRIMARY> db.getCollection('customer').find().forEach(function(cust){
... print("Customer Name : " + cust.name);
... print("Homes Contact : " + JSON.stringify(cust.phone[0]));
... print("Home Contact : " + cust.phone[0].home)
... })
Customer Name : Sam
Homes Contact : {"home":"123456","work":"045842"}
Home Contact : 123456

Mongodb connection to table in function

I don't know how should refer I to a table, maybe someone knows and can help:
Collection:
{
"_id" : ObjectId("5a5e40636494620e7471c51b"),
"uczelnia" : "Politechnika Wroclawska",
"ulica" : "Jodlowa 15",
"doktorzy" : [
{
"imie" : "Mateusz",
"nazwisko" : "Laskowski"
},
{
"imie" : "Piotr",
"nazwisko" : "Potrzebny"
}
],
"miejscowosc" : "Wroclaw"
}ObjectId("5a5e40636494620e7471c51b"
Function:
function dane_o_uczelni(id) {
uczelnia1= db.uczelnia.findOne({"_id" : id})
if(uczelnia1!==null)
{
print("Uczelnia: "+ uczelnia1.uczelnia)
print("Miejscowosc: " + uczelnia1.miejscowosc)
print("Doktorzy: " + uczelnia1.doktorzy.nazwisko)
}
else return null
}
dane_o_uczelni(ObjectId("5a5e40636494620e7471c51b"));
I want to see on output all of my Doctor(doktorzy) in ObjectId("5a5e40636494620e7471c51b" with surname (nazwisko). With this code I see only uczelnia and ulica, in nazwisko I see information undefined..

Tagging Multiple users in a Status in Titanium Mobile

Help me with tagging multiple Friend's with a status which I'm updating via my device from my app. Here's what I'm doing
var data = {
link : "http://www.appcelerator.com",
name : "Appcelerator Titanium (iteration " + iter + ")",
tags : ("1234","5678"),
accesstoken : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
message : "Awesome SDKs for building desktop and mobile apps ",
place : "XXXXXXXX",
caption : "Appcelerator Titanium (iteration " + iter + ")",
picture : "http://developer.appcelerator.com/assets/img/DEV_titmobile_image.png",
description : "You've got the ideas, now you've got the power. Titanium translates your hard won web skills..."
};
fb.requestWithGraphPath('me/feed', data, 'POST', showRequestResult);
When i run this only the 2nd user with the id above mentioned "5678",gets tagged and not the 1st user.
I also tried other methods like,
tags1 : {
'tags' : [{
"id" : "12345"
}, {
"id" : "12345"
}, {
"id" : "56789"
}, {
"id" : "457889"
}, {
"id" : "567890"
}, {
"id" : "987654"
}, {
"id" : "98765"
}]
},
I get an error in as (#100) param tags must be an array
I also tried this METHOD
var idnos = [];
idNos[0] = "123456";
idNos[1] = "4567";
idNos[2] = "456788";
idNos[3] = "45678989";
idNos[4] = "987654";
idNos[5] = "4567889";
tags = idnos
Parameter for the tag field should be an array. So instead of this:
var data = {
link : "http://www.appcelerator.com",
name : "Appcelerator Titanium (iteration " + iter + ")",
tags : ("1234","5678"),
accesstoken : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
message : "Awesome SDKs for building desktop and mobile apps ",
place : "XXXXXXXX",
caption : "Appcelerator Titanium (iteration " + iter + ")",
picture : "http://developer.appcelerator.com/assets/img/DEV_titmobile_image.png",
description : "You've got the ideas, now you've got the power. Titanium translates your hard won web skills..."
};
Use:
var data = {
link : "http://www.appcelerator.com",
name : "Appcelerator Titanium (iteration " + iter + ")",
tags : [{ "tag_uid":"1234" },{ "tag_uid":"5678" }],
accesstoken : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
message : "Awesome SDKs for building desktop and mobile apps ",
place : "XXXXXXXX",
caption : "Appcelerator Titanium (iteration " + iter + ")",
picture : "http://developer.appcelerator.com/assets/img/DEV_titmobile_image.png",
description : "You've got the ideas, now you've got the power. Titanium translates your hard won web skills..."
};

Powershell hashtable problem

I'm writing a script to take a string of letters and convert them to phonetic values. The problem I'm having is that I am unable to reference a value in a hashtable (see error below). I'm not sure why as the code looks fine to me.
Index operation failed; the array index evaluated to null.
At C:\Scripts\test.ps1:8 char:23
+ write-host $alphabet[ <<<< $char]
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArrayIndex
}
param($string = $(throw 'Enter a string'))
$alphabet = #{
"A" = "Alfa";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliett";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray";
"Y" = "Yankee ";
"Z" = "Zulu ";
}
clear-host
$charArray = $string.ToCharArray()
foreach ($char in $charArray)
{
write-host $alphabet[$char]
}
Each Char is a rich object, Change:
write-host $alphabet[$char]
to
write-host $alphabet["$char"]
or
write-host $alphabet[$char.ToString()]
Your problem is that in $alphabet[$char], $char is null. Where does $chararray come from?
Methinks you need to lose the space after each letter in your array. And you are also missing a space after Alfa, Juliett (sp), and X-ray.
$alphabet = #{
"A" = "Alfa ";
"B" = "Bravo ";
"C" = "Charlie ";
"D" = "Delta ";
"E" = "Echo ";
"F" = "Foxtrot ";
"G" = "Golf ";
"H" = "Hotel ";
"I" = "India ";
"J" = "Juliet ";
"K" = "Kilo ";
"L" = "Lima ";
"M" = "Mike ";
"N" = "November ";
"O" = "Oscar ";
"P" = "Papa ";
"Q" = "Quebec ";
"R" = "Romeo ";
"S" = "Sierra ";
"T" = "Tango ";
"U" = "Uniform ";
"V" = "Victor ";
"W" = "Whiskey ";
"X" = "X-ray ";
"Y" = "Yankee ";
"Z" = "Zulu ";
}