Reputation: 1297
let's say I have an structure like that in mongodb:
{
'source1': {
'name':'john',
'phone':'5555555'
}
'source2': {
'name':'john',
'city':'new york'
}
'source3': {
'name':'john',
'phone':'5555555'
'city':'new york'
}
}
how can I select all sources that have the 'phone' fields (source1 and source3)? something like *.phone {$exists:true}
Upvotes: 4
Views: 4920
Reputation: 53685
Basically you can't do it like you said "*.phone" in mongodb you should always specify field on what you try to do querying.
So one ugly solution can be manually check it in each source:
db.sources.find( { $or : [ { "source1.phone" : { $exists : true },
{ "source2.phone" : { $exists : true },
{ "source3.phone" : { $exists : true }]} };
But if you redesign your schema to be with one nested array of sources:
{
'sources': [{
'name':'john',
'phone':'5555555',
'source_name': "source1"
},
{
'name':'john',
'city':'new york',
'source_name': "source2"
}]
}
You can do it much more easier, following request return all sources that contains phone field:
db.sources.find({ "sources.phone" : { $exists : true })
Upvotes: 7