1

Let say, I have 2 collection

first one :-

db.product_main

{
  _id:123121,
  source_id:"B4456dde1",
  title:"test Sample",
  price: 250
  quantity: 40
}

which consist approx ~10000 objects (Array) and unique field is source_id.

Second :-

db.product_id

{
  "_id":58745633,
  "product_id":"B4456dde1"
}

which consist of ~500 and only have field "product_id" which is equals to "source_id" of db.product_main

now, i want to intersect two collection so that i only find those which don't exist in db.product_id.

db.product_main.aggregate({any query})

  • Please add the example document structure of each collection and post what have you tried so far – RaR Mar 11 '19 at 05:39
  • https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ – HIRA THAKUR Mar 11 '19 at 05:57
  • Possible duplicate of [How to join multiple collections with $lookup in mongodb](https://stackoverflow.com/questions/35813854/how-to-join-multiple-collections-with-lookup-in-mongodb) – HIRA THAKUR Mar 11 '19 at 06:03
  • my main objective is not to join but to find data which id do not exists in 2 table..... – Anshuman Singh Mar 11 '19 at 06:08

2 Answers2

2

Just use the lookup stage to find the products associated with the 'product_main' collection and then match for empty array (i.e. records where no product_id was found)

db.product_main.aggregate([
  {
    $lookup: {
      from: "product_id",
      localField: "source_id",
      foreignField: "product_id",
      as: "products_available"
    }
  },
  {
    $match: {
      products_available: {
        $size: 0
      }
    }
  }
])
Elvis
  • 1,103
  • 8
  • 15
0

On WRITE operations using aggregate pipeline You can also directly offload statistics update by using $out command and store cached result in product_stats collection (for example).

Later in web/ui/api READ operations just use this cached collection. Of cause, You can create database query methods for cached and non-cached results.