Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
MongoDB aggregation - combine multiple values of a document from collection A to lookup a single value within a document from collection B

Say I have the following two collections, sites and webpages. I'm trying to understand how to create an aggregation that'll allow me to combine values of a document from the sites collection and use that to lookup a value from the webpages collection. In addition, I need to prepend the combined values with a string.

// sites collection
[
  { "_id" : 3, "host" : "www.example-foo.com", "path": "/bar", "hasVisited": false },
]
// webpages collection
[
  { "_id" : 5, "url" : "https://www.example-foo.com/bar" },
  { "_id" : 8, "url" : "https://www.fizz.com/buzz" },
]

Without an aggregation I would do something like the following.

const site = await db.sites.findOne({ hasVisited: { $eq: false } });

const pages = await db.webpages.find({
  url: `https://${site.host}${site.path}`, // <--- how to construct this in a lookup aggregation? string + value + value
});
// pages = [{ "_id" : 5, "url" : "https://www.example-foo.com/bar" }]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is like translation of your code with the 2 find queries in 1 using $lookup

Query

  • first findOne is the $match and the $limit 1
  • $set url is to make the string concat
  • second find is to do the $lookup (with the 1 site from above stages)

*if you want to do it for more than 1 sites remove the limit, and project more fields, to know where this pages belong to(which site)

Test code here

db.sites.aggregate([
  {
    "$match": {
      "hasVisited": {
        "$eq": false
      }
    }
  },
  {
    "$limit": 1
  },
  {
    "$set": {
      "url": {
        "$concat": [
          "https://",
          "$host",
          "$path"
        ]
      }
    }
  },
  {
    "$lookup": {
      "from": "webpages",
      "localField": "url",
      "foreignField": "url",
      "as": "pages"
    }
  },
  {
    "$project": {
      "_id": 0,
      "pages": 1
    }
  }
])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda