Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-11865

A $findOne operator for $let,$map in $project phase

    • Type: Icon: New Feature New Feature
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • None

      A $findOne operator should be useful when data must be compiled from multiple collections.
      This is not like a "Collection JOIN Collection".
      It is more towards "From this document LOOKUP that document".

      	$findOne: {Options, Criteria, Projection}
      

      Options is

      {Collection:"name", Database:"db"}

      Criteria and Projection will be similar to db.collection.findOne() method.

      Take following sales order document for example:

      db.sales.findOne()
      	{
      		"_id" : 1,
      		"refcd" : "S1",
      		"date" : ISODate("2010-11-26T11:18:16.463Z"),
      		"cust" : {
      				"cid" : 10,
      				"doc" : "customer"
      		},
      		"lineitem" : [
      				{
      						"rowid" : 1,
      						"prod" : {
      								"pid" : 20,
      								"unitprice" : 41.37,
      								"doc" : "product"
      						},
      						"qty" : 26,
      						"linetotal" : 1075.62
      				}
      		],
      		"amount" : 1075.62
      	}
      

      To get the details from customer & product details for this document:

      	db.sales.aggregate([
      	{ $project: 
      			{
      				"_id":1,
      				"refcd":1,
      				"date":1,
      				"cust.cid":1,
      				"cust.doc":1,
      				"cust.ref":{$let: {vars:{}, in:{$findOne:{
      														{Collection:"$cust.doc"},
      														{"_id":"$cust.cid"},
      														{"_id":0}
      														}
      												}
      								} 
      						},
      				"lineitem":1,
      				"lineitem_ref": {$map: { input: "$lineitem",
      										as: "li",
      										in: {$findOne:{
      														{Collection:"$$li.prod.doc"},
      														{"_id":"$$li.prod.pid"},
      														{"_id":0}
      														}
      											}
      									}
      								},
      				"amount":1
      			}
      	}
      	])
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            zev23 Zev Teh
            Votes:
            3 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated:
              Resolved: