0

I have a MongoDB Collection such as the Given Below

{ "IslamabadICT": { "campus_name": "Islamabad", "campus_province": "ICT" }, "KarachiSindh": { "campus_name": "Karachi", "campus_province": "Sindh" }, "LahorePunjab": { "campus_name": "Lahore", "campus_province": "Punjab" }, "PeshawarKPK": { "campus_name": "Peshawar", "campus_province": "KPK" } } 

and I want to Query all the documents where campus_name='Lahore'. I'm running the following command

db.campus.find({"campus_name":"Lahore"}).pretty() but it returns nothing. The version of MondoDB is 3.4 and I'm running mongo shell.

Any suggestions ?

Thanks in Advance

2
  • Try this db.campus.find({"LahorePunjab.campus_name":"Lahore"}).pretty() Commented May 18, 2017 at 15:29
  • @Yogesh, that will not search for campus_name only, it'll first try to find the LahorePunjab field in document and If that fails it'll simply ignore the campus_name field value. Commented May 18, 2017 at 15:36

1 Answer 1

1

Here is the query that will return the document where campus_name='Lahore' -

db.campus.find().map( function(myDoc) { for (var key in myDoc) { if(key != "_id" && myDoc[key].campus_name == "Lahore"){ print( "Found it!!"); return myDoc; } } return null; } ).find(function(doc){if(doc!=null) return doc;}); 

Apart from this, I would highly recommend you to restructure your document format. One example could be to restructure the documents as follows -

{ { "main": "IslamabadICT", "campus_name": "Islamabad", "campus_province": "ICT" }, { "main": "KarachiSindh", "campus_name": "Karachi", "campus_province": "Sindh" }, { "main": "LahorePunjab", "campus_name": "Lahore", "campus_province": "Punjab" }, { "main": "PeshawarKPK", "campus_name": "Peshawar", "campus_province": "KPK" } } 

It will make the query a lot easier -

db.sht.find({campus_name:"Lahore"}).pretty() 

Which is the one you tried in first place. :)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks.....I changed the format of my Collection, it's working well now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.