从 Mongodb 中的对象数组中查找对象
finding object from array of objects in Mongodb
const Schema = new Schema({
queueId: {
type: String,
required: true,
index: {
unique: true
}
},
players: {
type: [
{
ID: {
type: String,
required: true,
index: {
unique: true
},
default: 'null'
},
name: {
type: String,
required: true,
default: 'null',
},
queueId: {
type: String,
required: true,
default: 'null'
}
}
],
required: true,
default: []
},
isAvailable: {
type: Boolean,
required: true,
default: true
},
isFull: {
type: Boolean,
required: true,
default: false
}
});
如何使用 findOne()
从数组 players
中获取对象
我目前正在尝试此代码,但它 returns null
const doc = await List.findOne({ players: { ID: 'id' } });
基本上 players
是一个数组,我想从玩家对象数组中找到 ID 并获取文档。
db.collection.find({
"players.ID": "1"
},
{
"players.$": 1
})
db.collection.find({
"players.ID": "1"
})
db.collection.aggregate([
{
$match: {
"players.ID": "1"
}
},
{
$unwind: "$players"
},
{
$match: {
"players.ID": "1"
}
}
])
const Schema = new Schema({
queueId: {
type: String,
required: true,
index: {
unique: true
}
},
players: {
type: [
{
ID: {
type: String,
required: true,
index: {
unique: true
},
default: 'null'
},
name: {
type: String,
required: true,
default: 'null',
},
queueId: {
type: String,
required: true,
default: 'null'
}
}
],
required: true,
default: []
},
isAvailable: {
type: Boolean,
required: true,
default: true
},
isFull: {
type: Boolean,
required: true,
default: false
}
});
如何使用 findOne()
从数组 players
中获取对象
我目前正在尝试此代码,但它 returns null
const doc = await List.findOne({ players: { ID: 'id' } });
基本上 players
是一个数组,我想从玩家对象数组中找到 ID 并获取文档。
db.collection.find({
"players.ID": "1"
},
{
"players.$": 1
})
db.collection.find({
"players.ID": "1"
})
db.collection.aggregate([
{
$match: {
"players.ID": "1"
}
},
{
$unwind: "$players"
},
{
$match: {
"players.ID": "1"
}
}
])