在下面的mongo集合中,如何过滤包含密钥cat1
的文档?
{
"_id" : ObjectId("xxxxxxxxxx"),
"key1_cat1": "val1"
}
{
"_id" : ObjectId("xxxxxxxxxx"),
"key1_cat2": "val2"
}
{
"_id" : ObjectId("xxxxxxxxxx"),
"key2_cat1": "val3"
}
{
"_id" : ObjectId("xxxxxxxxxx"),
"key2_cat2": "val4"
}
我正在寻找像collection.find({"$key_contains":"cat1"})
这样的东西,它应该过滤doc1和doc2并输出为
{
"_id" : ObjectId("xxxxxxxxxx"),
"key1_cat1": "val1"
}
{
"_id" : ObjectId("xxxxxxxxxx"),
"key2_cat1": "val3"
}
答案 0 :(得分:1)
我相信它不能直接在Mongo中完成。但我们可以使用聚合来实现这一点,使用objectToArray
collection.aggregate([{
'$project': {
modifiedFormat: {
$objectToArray: '$$ROOT' // converts your object to array format [{k:, v:}, {k:, v:}]
}
}
}, {
$match: {
'modifiedFormat.k': {
$regex: 'cat1' // your search on key(k)
}
}
}, {
$project: {
oldFormat: {
$arrayToObject: '$modifiedFormat' // Making array to object again
}
}
}, {
$replaceRoot: {
newRoot: '$oldFormat' // replaceRoot to bring in the old format
}
}])