drsealks
drsealks

Reputation: 2354

How to use aggregation results as an input to a find query?

Suppose I have the following aggregation statement in monogdb console:

ids = db.articles.aggregate([
  {'$group':{'_id':'1','ids':{$push:{'$toString':'$ref_id'}}}},
  {'$project': {'ids':true,'_id':false}},
])

The result of this aggregation looks something like(output truncated):

[
  {
    "ids": ["5ebadde78da8f3de641064a5", "5ebaddec8da8f3de641064b7", "5ebaddec8da8f3de641064c9"]
  }
]

My question is how can I (if at all possible) use this aggregation result to find objects in another collection _ids of which do not appear in the aggregation results. Here is an illustrative (non-working) example of what I'm trying to do:

db.another_collection.countDocuments({'_id':{$nin:ids['ids']}})

What would be a good way to approach this problem?

Upvotes: 0

Views: 880

Answers (2)

Valijon
Valijon

Reputation: 13103

Try this one:

db.articles.aggregate([
  {
    "$group": {
      "_id": "1",
      "ids": {
        "$push": {
          "$toString": "$ref_id"
        }
      }
    }
  },
  {
    $lookup: {
      from: "another_collection",
      localField: "ids",
      foreignField: "_id",
      as: "tmp"
    }
  },
  {
    "$project": {
      total: {
        $size: {
          $filter: {
            input: "$ids",
            cond: {
              $not: {
                $in: [
                  "$$this",
                  "$tmp._id"
                ]
              }
            }
          }
        }
      }
    }
  }
])

MongoPlayground

Upvotes: 2

prasad_
prasad_

Reputation: 14317

The aggregation with $lookup ("joins" two collections articles and another_collection) to count the documents in the another_collection which are not in the articles.

db.another_collection.aggregate( [
  { 
      $lookup: {
           from: "articles",
           localField: "_id",
           foreignField: "ref_id",
           as: "matches"
      }
  },
  { 
      $match: { matches: { $size: 0 } } 
  },
  { 
      $count: "Document Count" 
  }
] )

Sample articles documents:

{ _id: 1, ref_id: "5ebadde78da8f3de641064a6" }
{ _id: 2, ref_id: "5ebaddec8da8f3de641064c9" }
{ _id: 3, ref_id: "5ebaddec8da8f3de641064b7" }

Sample another_collection documents:

{ "_id" : "5ebadde78da8f3de641064a5" }
{ "_id" : "5ebadde78da8f3de641064a6" }
{ "_id" : "5ebadde78da8f3de641064a4" }

The result: { "Document Count" : 2 } - these are the two documents with _id values "5ebadde78da8f3de641064a5" and "5ebadde78da8f3de641064a46".

Upvotes: 1

Related Questions