我想对该集合执行查询,以确定哪些文档在与某个值匹配的事物中具有任何键。这可能吗?
我有一组文档,例如:
{
"things": {
"thing1": "red",
"thing2": "blue",
"thing3": "green"
}
}
编辑:为了简洁
最佳答案
如果您不知道键是什么并且您需要它是交互式的,那么您需要使用(众所周知的性能挑战)$where
像这样的操作符(在 shell 中):
db.test.find({$where: function() {
for (var field in this.settings) {
if (this.settings[field] == "red") return true;
}
return false;
}})
如果您的集合很大,这可能对您的目的来说太慢,但如果您的 key 集未知,这是您唯一的选择。
MongoDB 3.6 更新
您现在可以在不使用 $where
的情况下使用 $objectToArray
来执行此操作。聚合运算符:
db.test.aggregate([
// Project things as a key/value array, along with the original doc
{$project: {
array: {$objectToArray: '$things'},
doc: '$$ROOT'
}},
// Match the docs with a field value of 'red'
{$match: {'array.v': 'red'}},
// Re-project the original doc
{$replaceRoot: {newRoot: '$doc'}}
])
https://stackoverflow.com/questions/19802502/
相关文章:
sql - 为什么 MongoDB 比 SQL DB 快得多的任何详细和具体原因?
mongodb - $cond 中存在 $exists 的条件分组
node.js - 如何检查MongoDB native nodejs驱动程序中是否存在集合?
php - 安装 PHP 7 MongoDB 客户端/驱动程序?
mongodb - 在 Mongo 中,如何显示集合的索引?
sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
mongodb - 在 MongoDB 中创建自定义对象 ID
c# - MongoDB C# 驱动程序 : Ignore Property on Insert