0

I am trying to connect two API, so my scenario is get data from API_1 and then post it to API_2. I put the data I get from API_1 in items collection

db.items.find()
{ "_id" : ObjectId("5af4a47f3bfab813b9b7396d"), "poId" : "4739521", "sku" : "PTES02", "qtty" : 99, "prc" : 10, "__v" : 0 }
{ "_id" : ObjectId("5af4a47f3bfab813b9b7396e"), "poId" : "4739539", "sku" : "PTES01", "qtty" : 13, "prc" : 99, "__v" : 0 }
{ "_id" : ObjectId("5af4a4b573c9ab13ce2ef78d"), "poId" : "4739521", "sku" : "PTES02", "qtty" : 99, "prc" : 10, "__v" : 0 }
{ "_id" : ObjectId("5af4a4b573c9ab13ce2ef78e"), "poId" : "4739539", "sku" : "PTES01", "qtty" : 13, "prc" : 99, "__v" : 0 }

I want to add the Variant ID from variants collections (which I get, from API_2) based on its SKU because it is required by API_2 in order to post, and both variant ID in API_1 and API_2 is completely different:

> db.variants.find()
{ "_id" : ObjectId("5af48bd03697230e01503eb2"), "SKU" : "PTES02", "varrID" : "40035121", "__v" : 0 }
{ "_id" : ObjectId("5af48bd03697230e01503eb3"), "SKU" : "PTES01", "varrID" : "39183757", "__v" : 0 }

I tried this aggregation:

db.items.aggregate([
  { 
    $lookup: { 
      from: "variants",
      localField: "sku",
      foreignField: "SKU",
      as: "VardId"
    }
  },
  {
    $out: "VariantID"
  }
])

It creates a new empty collection named "VariantID" in database outside items collection, instead of this result that I want to achieve:

{
   "_id" : ObjectId("5af4a47f3bfab813b9b7396d"),
   "poId" : "4739521",
   "sku" : "PTES02",
   "qtty" : 99,
   "prc" : 10,
   "VariantID": "40035121",
   "__v" : 0
}

Please help me, GREAT GREAT Thanks!

vypr
  • 1
  • Are you trying to create a new collection, or what exactly? `$out` creates a new collection. It's not clear what you are asking here or what your problem actually is. – Neil Lunn May 13 '18 at 09:55
  • Hi @NeilLunn, I am trying to get that VariantID to be a field of items collection – vypr May 13 '18 at 09:57
  • So you want to "update" the "existing" collection? Put the new field in "items"? – Neil Lunn May 13 '18 at 09:57
  • Yes correct! What do I do wrong? – vypr May 13 '18 at 09:59
  • `$out` cannot write to the existing collection. If you want to update the existing collection then you need to actually loop the results. If you use `$out` you have no choice but to have a new collection. – Neil Lunn May 13 '18 at 10:01
  • Okay @NeilLunn, Great thanks! Will try your solution – vypr May 13 '18 at 10:02

0 Answers0