【问题标题】:how to select a property depending another property - mongodb如何根据另一个属性选择一个属性 - mongodb
【发布时间】:2019-09-21 17:21:18
【问题描述】:

我正在使用mongoose。我想根据此处type 的另一个属性选择users 属性。

例如当我的typeprivate 我想选择users

Conversation.find({
users: {
$elemMatch: {
user: _id
  }
 }
},{
 title: 1,
 type: 1,
 users:1 // when `type` is `private` I want to this field to be one.
});

我的架构:

const ConversationSchema = new Schema({
    type: {type: String, enum: ['private', 'group'], default: 'private'},
    creator: {type: Schema.Types.ObjectId, ref: 'User', index: true, required: true}, // creator
    // for group,
    title: String, 
    picture: String,
    description: String,
    users: [
        {
            user: { type: Schema.Types.ObjectId, index: true, reuqired:  true, unique: true }, 
            role: { type: String, enum: ['admin', 'member'], default: 'member' },
            mute: { type:  Boolean, default: false },
            type: {type: String, enum: ['private', 'group'], default: 'private'},
        }
    ],
}, { timestamps: true });

【问题讨论】:

  • 嗨,你能分享你的架构吗?

标签: node.js mongodb mongoose


【解决方案1】:

您可以通过在聚合中使用REMOVEconditionally exclude fields。在你的情况下,它应该是:

Conversation.aggregate([
  {$match: {"users.user": id}},
  {
     $project: {
       title: 1,
       type: 1,
       users: {
         $cond: { 
           if: { $eq: [ "$type", "private" ] }, 
           then: "$users", 
           else: "$$REMOVE" 
         }
       }
     }
  }
])

旁注:如果在$elemMatch 表达式中只指定一个条件,则不需要使用$elemMatch

【讨论】:

    【解决方案2】:

    您可以像这样使用聚合,如果您想要用户详细信息,它将选择所有用户,然后必须使用填充。

    db.getCollection("Conversation").aggregate([
        {
            $unwind: "$users"
        },
        {
            $match: {
                "type": 'private'
            }
        }
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多