PHP MongoDB。检查嵌入文档是否包含整数

标签 php mongodb

我是 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"
            }
          }
        }
      },
      []
    ]
  }
})

Playground

  • 如果我没记错的话,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/

相关文章:

mongodb - 如何在 mongoDB 中聚合巨大的数组?

php - Android Eclipse 如何将php MySql数据库中的特定数据显示到 ListView

php - 保护和加密客户端和服务器之间的连接

php - 如何显示已确认的好友

php - SQL/Wordpress/AJAX : Format JSON With Loop

mysql - 哪个数据库用于存储文件路径?

mongodb - MongoDB-子代和父代结构

shell - 如何在 mongodb shell 查询中使用 guid

php - 如何使用准备好的语句按时间排序?

node.js - 如何使用 Node JS 将 mongoDB 查询记录到终端