$lookup on ObjectId's in an array

后端 未结 6 1653
忘了有多久
忘了有多久 2020-11-22 04:53

What\'s the syntax for doing a $lookup on a field that is an array of ObjectIds rather than just a single ObjectId?

Example Order Document:

{
  _id:          


        
6条回答
  •  心在旅途
    2020-11-22 05:29

    Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

    var mongoose = require("mongoose"),
        Schema = mongoose.Schema;
    
    var productSchema = Schema({ ... });
    
    var orderSchema = Schema({
      _id     : Number,
      products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
    });
    
    var Product = mongoose.model("Product", productSchema);
    var Order   = mongoose.model("Order", orderSchema);
    
    ...
    
    Order
        .find(...)
        .populate("products")
        ...
    

提交回复
热议问题