I am a Beginner in MongoDB and I hope my following question is clear to all.
Consider the following document-
{
'_id': ObjectId("A"),
components:[
0: {
index: 21,
abc:22,
person: [
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'},
{id:25, first:'Jill',last:'Ryan', location:'USA,New Jersey'},
{...}
]
},
1: {
index: 22,
abc:23,
person: [
{id:12, first:'Andy',last:'Sparrow', location:'USA,New York'},
{id:14, first:'Kate',last:'Ryan', location:'USA,New Jersey'},
{...}
]
},
]
}
Now I am trying to write a MongoDB query to perform regex operations on the person array in my document so that I get the following answer
{
person:[
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'}
]
}
OR
{
components:[
person:[
{id:23, first:'Jack',last:'Sparrow', location:'USA,New York'},
{id:24, first:'Jack',last:'Ryan', location:'USA,New Jersey'}
]
]
}
I thought that since its a deeply nested query its better to use aggregate.
1st Try:
db.collection.aggregate(
{'$unwind': '$components'},
{'$match' :
'_id': ObjectId("A"),
'components.index':'21',
'components.first':{'$regex':'^ja'}
}
)
But this doesn't seem to work. I want to use regex strictly for my case to work. I tried to do the same thing with the location field.
2nd Try: I also tried doing the same thing as above and adding to the aggregate Pipeline another unwind for Person Array like following.
db.collection.aggregate(
{'$unwind': '$components'},
{'$match' :
'_id': ObjectId("A"),
'components.index':'21',
'components.first':{'$regex':'^ja'}
},
{'$unwind': '$components.person'},
)
But this didn't change anything.
My Questions:
1) Is it possible to do this?
2) Is there a solution for this using find query?
3) If I want to unwind person array, How to do it?(Unwind deeply nested array)
4) How do I use Regex in this situation?