如何根据另一个属性选择属性 - MongoDB



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

例如,当我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 });

您可以通过在聚合中使用 REMOVE 有条件地排除字段。在您的情况下,它应该是:

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

旁注:如果在$elemMatch表达式中仅指定单个条件,则无需使用$elemMatch

你可以像这样使用聚合,如果你想用户的详细信息,它将选择所有用户,然后将不得不使用填充。

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

最新更新