0

I'm using native mongodb driver on nodejs and I wish to be able to run a single query and retrieve all documents from another collection.

I have a tags collection: id_, tag and on my article collection I have tagsthat is an array of ObjectId

Array of ObjectId

now, when I retrieve the correct document I wish to have tagsholding the tag value on the tagscollection.

I can't wrap my head around that, I've been trying this but it only retrieves the first tag:

  db.orders.aggregate([
     {
        $unwind: "$tags"
     },
     {
        $lookup:
           {
              from: "tags",
              localField: "tags",
              foreignField: "_id",
              as: "tags_found"
          }
     },
     {
        $match: { "tags_found": { $ne: [] } }
     }
  ])

Is there a way to retrieve all the tags at once? If not, what is the best way to do so without using Mongoose but the native driver?

chridam
  • 100,957
  • 23
  • 236
  • 235
sathia
  • 2,192
  • 2
  • 24
  • 42

1 Answers1

0

By looking at another question here on SO I almost managed to obtain what I wanted, thanks @chridam

Unfortunately it doesn't find articles without tags. is there a way to do that?

db.getCollection('articles').aggregate([
     {
        $unwind: "$tags"
     },
     {
        $lookup:
           {
              from: "tags",
              localField: "tags",
              foreignField: "_id",
              as: "tags_found"
          }
     },
      {
        $unwind: "$tags_found"
     },
     { "$group": {
        "_id": "$_id",
        "tags": { "$push": "$tags" },
        "tags_found": { "$push": "$tags_found" }
    }},
     {
        $match: { "tags_found": { $ne: [] } }
     }
  ])
sathia
  • 2,192
  • 2
  • 24
  • 42