skip to Main Content

I have two tables, a user table and an order table. Now, if I want to query the orders of all the users whose appid is 1, how do I query them

const orderSchema = new mongoose.Schema({
    user: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "User",
        required: true
    },
    orderNum: {
        type: String,
        required: true
    },
})
const UserSchema = new mongoose.Schema({
    nickname: String,
    avatarUrl: String,
    phone: String,
    appId: {
        type: String,
    }
});

2

Answers


  1. You can use the following aggregation pipeline:

    orderSchema.aggregate([
      {
        "$lookup": {
          "from": "User",
          "localField": "user",
          "foreignField": "_id",
          "as": "user"
        }
      },
      {
        $match: {
          "user.0.appId": "1"
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search