使用的都是MongoDb的原生查询语法,示例:
$args = [
['user_id' => 10002, 'contact' => '17900010178'],
['user_id' => 10206, 'contact' => '17002717568'],
];
$cts = $filter = [];
foreach ($args as $key => $arg) {
$cts[] = $arg['contact'];
$filter['$or'][] = [
'user_id' => ['$eq' => $arg['user_id']],
'list' => [
'$elemMatch' => [
'contacts' => [
'$elemMatch' => [
"contact" => ['$eq' => $arg['contact']]
]
]
]
]
];
}
$options = [
'projection' => [
'user_id' => 1,
'list.name' => 1,
'list.contacts.contact' => 1,
],
];
$readPreference = new \MongoDB\Driver\ReadPreference(1);
$query = new \MongoDB\Driver\Query($filter, $options);
$list = Db::connect('db_mongo')->query('data-mongo.contacts', $query, $readPreference);
说明:
- $fillter 为查询条件,如 $eq、$gt 等
- $options 为可选参数,如 projection、sort 等
- ReadPreference 类为设置数据来源操作,参考官网
- Query 类为MongoDb的查询类,参考官网
- 以上查询对应的SQL类似如下:
select user_id, name, contact
from data-mongo.contacts
where (user_id = 1002 and list.contacts.contact = 17900010178)
or (user_id = 10206 and list.contacts.contact = 17002717568)
问题:
- 本来是想只返回数组中匹配的第一个元素的,但在使用了 $or 条件后,就无法使用 $ 定位符了,参考Mongodb官网说明
还有一个类 : \MongoDB\Driver\Command 也可以做这个,不懂区别在哪!