【发布时间】:2016-02-26 12:45:41
【问题描述】:
我有一个带有用户键的数组。
ID 为:array('111', '333');的用户
我会得到以下方案,只有具有这些 id 的用户的一些字段(名称)。
{
"_id" : "78787878",
"users" : {
"111" : {
"name" : "William",
"e" : "w@sas..."
...
},
"222" : {
"name" : "Sarah",
"e" : "s@sas..."
},
"333" : {
"name" : "Marie",
"e" : "m@sas..."
},..
},..
}
我的预期结果是这样的:
{
"_id" : "78787878",
"users" : {
"111" : {
"name" : "William",
},
"333" : {
"name" : "Marie",
}
}
}
我试过了:
db.getCollection('instagram').find({'_id' : '78787878', 'users' : { '$in' : ['456726', '2945551665'] } }, { '_id' : 0, 'users.name' : 1 })
如何进行此类查询?我可以使用“findOne”还是应该使用“聚合”?
已编辑(问题仍在继续):
如果我按如下方式修改架构,则根据 cmets:
{
"_id" : "78787878",
"users" : [
{
"id": 111,
"name" : "William",
"e" : "w@sas..."
...
},
{
"id": 222,
"name" : "Sarah",
"e" : "s@sas..."
},
{
"id": 333,
"name" : "Marie",
"e" : "m@sas..."
},..
]
}
如果我使用 $in 它会返回所有... 为什么不应用过滤器?
$filter = array(111, 333);
$this->db->{$collection}->find(array('_id' => '78787878', 'users.id' => array('$in' => $filter)), array('users' => 1));
users.id 是 Int32。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework mongodb-php