Concat字段合二为一

时间:2019-01-08 19:48:16

标签: node.js mongodb mongodb-query aggregation-framework

我在下面有这个查询:

var query = {
    $and:
    [
        {
            uf:
            {
                $exists: true,
                $ne: ""
            }
        },
        {
            municipio:
            {
                $exists: true,
                $ne: ""
            }
        },
        {
            $or:
                [
                    {
                        email:
                        {
                            $exists: true,
                            $ne: ""
                        }
                    },
                    {
                        telefone:
                        {
                            $exists: true,
                            $ne: ""
                        }
                    }
                ]
        },
    ]
}

var mod = {
    atividade_principal: 1,
    $concat: [
        "$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ", ", "$cep",
    ],
    telefone: 1,
    email: 1,
    qsa: 1,
    nome: 1,
    natureza_juridica: 1,
    tipo: 1
}

db.empresas.find(query, mod).limit(1000);

,我要保留这一行:

$concat: [
    "$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ", ", "$cep",
]

但是正如我所看到的那样,find()函数中不允许这样做,但是我不知道如何使用聚合来做到这一点,因为聚合框架表明它所允许的是获取许多文档并将其转换为一个文档将所有其他文档归为一组,如果我错了,请澄清一下。

谢谢!

1 个答案:

答案 0 :(得分:1)

findaggregate函数之间没有这种区别。聚合只是用来重塑数据而已。还有一些运算符可用于重整聚合函数中的数据。

在查找查询中,第一个参数用于过滤器,第二个参数用于投影,并且$match$project在聚合中的作用相同

const query = {
  "$and": [
    { "uf": { "$exists": true, "$ne": "" } },
    { "municipio": { "$exists": true, "$ne": "" }},
    {
      "$or": [
        { "email": { "$exists": true, "$ne": "" }},
        { "telefone": { "$exists": true, "$ne": "" }}
      ]
    }
  ]
}

const projection = {
  "atividade_principal": 1,
  "concatinatedField": { "$concat": ["$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ",", "$cep"] },
  "telefone": 1,
  "email": 1,
  "qsa": 1,
  "nome": 1,
  "natureza_juridica": 1,
  "tipo": 1
}

db.empresas.aggregate([
  { "$match": query },
  { "$limit": 1000 },
  { "$project": projection }
])