title: Combined lookup and embed in the same MongoDB collection depending on root document structure
body: <p>I want to make a conditional lookup with Mongo in the following way: a root document contains either a link (<code>customerId</code>) to the <code>customers</code> collection or directly embeds a customer, like this:</p>
  
  <pre><code>{
    "_id" : 1,
    "item": "item1",
    "customer": { _id: 1, "name": "Jane Doe" }
  },
  {
     "_id":  2,
     "item": "item2",
     "customerId": 1
  }
  </code></pre>
  
  <p>customers collection: </p>
  
  <pre><code>{ _id: 1, "name": "Jane Johnson" }
  </code></pre>
  
  <p>The <code>customers</code> collection stores the current versions of customers; to maintain consistency, members of the <code>items</code> collection will contain just ids of customer. But if I want to freeze an item so it holds <em>the</em> version of its customer at a certain time, I will embed that <code>customer</code> directly into the <code>item</code> in question.</p>
  
  <p>When searching for <code>items</code> I want them to appear uniformly (i.e. regardless whether customer is looked up or embedded it will appear as embedded field):
  e.g.</p>
  
  <pre><code>[{
    "_id" : 1,
    "item": "item1",
    "customer": { _id: 1, "name": "Jane Doe" } // historical version of Jane (embedded)
  },
  {
     "_id":  2,
     "item": "item2",
     "customer": { _id: 1, "name": "Jane Johnson" } // current version of Jane by lookup
  }]
  </code></pre>
  
  <p>Question 1: is this the right approach and if not what is the best practice for handling cases like this? 
  Question 2: if my approach is correct, how to best use aggregation framework to achieve this? 
  Thanks!</p>