我是 MongoDB 新手,正在尝试在嵌入文档中进行整数搜索。我的收藏如下
db.inventory.insertMany([{
"store": "abc store",
"games": [{
"gameId": 12254,
"score": 88
},
{
"gameId": 12258,
"score": 70
},
{
"gameId": 12262,
"score": 98
}
]
}, {
"store": "xyz store",
"games": [{
"gameId": 18244,
"score": 88
},
{
"gameId": 18248,
"score": 25
},
{
"gameId": 18252,
"score": 66
}
]
}]);
我想在集合中搜索例如 games.gameId
中的 122
并获得以下结果
[{
"store": "abc store",
"games": [{
"gameId": 12254,
"score": 88
},
{
"gameId": 12258,
"score": 70
},
{
"gameId": 12262,
"score": 98
}
]
}]
最佳答案
$filter
迭代games.gameId
数字数组的 loo$toString
将数字转换为字符串$regexMatch
匹配上面转换后的字符串有任何“122”字符串$ne
,过滤结果不能为空[]$expr
是使用聚合运算符的表达式条件
db.collection.find({
$expr: {
$ne: [
{
$filter: {
input: "$games.gameId",
cond: {
$regexMatch: {
input: { $toString: "$$this" },
regex: "122"
}
}
}
},
[]
]
}
})
- 如果我没记错的话,php 语法
$query = [
'$expr' => [
'$ne' => [
[
'$filter' => [
"input" => '$games.gameId',
"cond" => [
'$regexMatch' => [
"input" => ['$toString' => '$$this'],
"regex" => "122"
]
]
]
],
[]
]
]
];
$cursor = $collection->find($query);
关于PHP MongoDB。检查嵌入文档是否包含整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67603950/