Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

mongo db get child result with array of parent ids

db.collection.aggregate([
  {
    $match: {
      tags: "b", // add your search
      childs: { $ne: [] }
    }
  },
  {
    $lookup: {
      from: "collection",
      let: { childs: "$childs" },
      as: "ids",
      pipeline: [
        {
          $match: {
            $expr: { $in: ["$id", "$$childs"] },
            tags: { $ne: "b" } // add your search
          }
        }
      ]
    }
  },
  {
    $project: {
      id: 1,
      ids: {
        $reduce: {
          input: "$ids",
          initialValue: [],
          in: { $concatArrays: ["$$value", ["$$this.id"]] }
        }
      }
    }
  }
])
 
PREVIOUS NEXT
Tagged: #mongo #db #child #result #array #parent #ids
ADD COMMENT
Topic
Name
1+2 =