Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb:查询列出至少有5个字段不等于null或“0”的记录&引用;或具有4';X';s_Mongodb - Fatal编程技术网

Mongodb:查询列出至少有5个字段不等于null或“0”的记录&引用;或具有4';X';s

Mongodb:查询列出至少有5个字段不等于null或“0”的记录&引用;或具有4';X';s,mongodb,Mongodb,我有一个包含5个字段的集合: 巧克力、饼干、薄饼、松露、薄荷糖 每个字段的值为X、null或“” 我正在尝试列出至少有4个“X”的所有记录。我为此查询使用了此解决方案: db.getCollection("stores").aggregate([ { $addFields: { fieldsToMatch: ["$chocolates", "$biscuits", "$wafers", "$truffles", "$mints"] } }, { $unw

我有一个包含5个字段的集合:

巧克力、饼干、薄饼、松露、薄荷糖

每个字段的值为X、null或“”


我正在尝试列出至少有4个“X”的所有记录。

我为此查询使用了此解决方案:

db.getCollection("stores").aggregate([
{
    $addFields: {
        fieldsToMatch: ["$chocolates", "$biscuits", "$wafers", "$truffles", "$mints"]
    }
},
{
    $unwind: "$fieldsToMatch"
},
{
    $match: {
        fieldsToMatch: "X"
    }
},
{
    $group: {
        _id: "$name",
        count:{$sum:1}
    }
},
{
    $match: {
        count: {
            $gte: 4
        }
    }
}])
我基本上是将所有的值添加到一个数组“fieldsToMatch”,然后使用unwind操作符为数组中的每个元素创建几个记录,匹配它等于X的元素,按名称(或_id)分组和计数,最后匹配至少出现4次的元素

这种方法的唯一问题是只返回符合条件的文档的_id,要获取整个文档,需要使用查找或再次查询集合

希望这有帮助

此输入:

var r = [
{store: "A", chocolate:"X", biscuits:"X", wafers: "X", truffles:"X", mints:"X"},
{store: "B", chocolate:null, biscuits:"", wafers: "X", truffles:"X", mints:"X"},
{store: "C", chocolate:null, biscuits:"", wafers: "", truffles:"X", mints:"X"},
{store: "D", chocolate:"X", biscuits:"", wafers: "X", truffles:"X", mints:"X"}
         ];

db.foo.insert(r);
将产生预期的结果
$reduce
是一个强大的面向数组的函数。在下面的用例中,我们说“对于字段列表中的项,如果它等于X,则添加1,否则添加0;完成后,N是结果。”


对于大型集合,这可能会变得有点慢,因为在开始处理之前,它会产生5倍的数据爆炸。在得到公认的答案后,不要羞于给它投票。;-)
db.foo.aggregate([
{$addFields: {N: {$reduce: {
                input: ["$chocolate","$biscuits","$wafers","$truffles","$mints"],
                initialValue: 0,
                in: {$sum: [ "$$value", {"$cond":[ {"$eq": ["$$this","X"]}, 1, 0]} ]}
            }}
    }}
,{$match: {"N": {$gte:4} }}
                    ]);

{
    "_id" : ObjectId("5dda931f76e431f9c9169859"),
    "store" : "A",
    "chocolate" : "X",
    "biscuits" : "X",
    "wafers" : "X",
    "truffles" : "X",
    "mints" : "X",
    "N" : 5
}
{
    "_id" : ObjectId("5dda931f76e431f9c916985c"),
    "store" : "D",
    "chocolate" : "X",
    "biscuits" : "",
    "wafers" : "X",
    "truffles" : "X",
    "mints" : "X",
    "N" : 4
}