首页 文章

如何在字符串字段和ObjectId之间进行查找 - MongoDB C#Driver

提问于
浏览
0

我有这些收藏:

1 - 订单:

{ 
    "_id" : ObjectId("5ac68963b305462bc88150f6"), 
    "ClientId" : "5aabc24bb3054633a4053a9f" 
}

2 - 客户:

{ 
    "_id" : ObjectId("5aabc24bb3054633a4053a9f"), 
    "Name" : "Tiago", 
    "Email" : "tiago@email.com", 
}

我想从客户端引入订单,数据 . 但是因为ClientId是一个字符串而Client中的_id是一个ObjectId,所以我不能在那之间进行查找 .

我正在使用MongoDB C#Driver,这是我的代码,直到现在:

var order = _database.GetCollection<Order>.Aggregate().Match(myFilter).Lookup("Client", "ClientId", "_id", "MyPropertyToFill").As<Order>().FirstOrDefault();

有关如何做到这一点的任何想法?

1 回答

  • 2

    在您的模型中,您必须将iClientId定义为ObjectId,如下所示:

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema
    
    const Order = new Schema({
      iClientId: Schema.Types.ObjectId
      // Rest of the Field
    })
    
    module.exports = mongoose.model('order', Order)
    

    现在在您要执行查找的文件中

    const mongoose = require('mongoose')
    const ObjectId = mongoose.Types.ObjectId
    
    Model.aggregate([
      {$match: {_id: ObjectId('filter_id')}},
      {$lookup: {
        from: 'client',
        localField: 'ClientId',
        foreignFiled: '_id',
        as: 'fromclient'
      }}
    ], (err, result) => {
     // Your action
    })
    

    这是如何实现这一点的,我用猫鼬做到了,但你也可以做到没有猫鼬 .

相关问题