[英]retrieve multiple objects from one which is array of objects in mongodb
我使用mongodb来保存用户数据和数组。 我的问题是如何检索与该用户数组中给定值匹配的多个对象,如下所示:
{
_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
}
]
}
结果是
{
_id: { objid: '0000000000000' },
userId: 'abc',
userItems: [
{
itemName: 'mango',
date: 24,
month: 1,
year: 2016
},
{
itemName: 'apple',
date: 24,
month: 1,
year: 2016
}
]
}
我想要所有与此userId userItems数组中的date,month,year匹配的元素,请帮助我
我们可以通过聚合框架找到结果。
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'
}
}
}
)
有关更多详细信息和示例,请参见$ elemMatch文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.