I using mongodb to save my user data along with array. My question is how to retrieve multiple objects that matches the given value in that user array.like this:
{
_id: { objid:'0000000000000' },
userId: 'abc',
userItems : [
{
itemName: 'mango',
date: 24,
month: 1,
year: 2016
},
{
itemName: 'apple',
date: 24,
month: 1,
year: 2016
},
{
itemName: 'orange',
date: 22,
month: 1,
year: 2016
},
{
itemName: 'vanilla',
date: 23,
month: 1,
year: 2016
}
]
}
and expeccted result is
{
_id: { objid: '0000000000000' },
userId: 'abc',
userItems: [
{
itemName: 'mango',
date: 24,
month: 1,
year: 2016
},
{
itemName: 'apple',
date: 24,
month: 1,
year: 2016
}
]
}
I want all the element that matches the date,month,year from this userId userItems array please help me out from this
We can find result by aggregation framework.
db.user.aggregate(
{
$unwind : "$userItems"
},
{
$match: {
"userItems.date" : 24,
"userItems.month" : 1,
"userItems.year" : 2016
}
},
{
$group: {
"_id" : { "id":"$_id","userId":"$userId"},
"userItems" : {$push:"$userItems"}
}
},
{
$project:{
"_id": "$_id.id",
"userId": "$_id.userId",
"userItems": 1
}
}
)
db.collectioName.find(
{
nameOfArrayYouarelookingIn: {
$elemMatch: {
ArrayFieldOneName: 1,
ArrayFieldTwoName: 'blahblah'
}
}
}
)
See $elemMatch documentation for more details and examples.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.