在数组mongo中过滤数组中的数据



我有这样的数据结构:

{
date: 0,
darwin: [
{
d: ['string1', 1, 0, 0, 0]
},
{
d: ['string2', 1, 0, 0, 0]
},
{
d: ['string3', 1, 0, 0, 0]
}
]
}

和这个schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;
const dataSchema = new Schema({
date: { type: Number, required: false, unique: true, index: true },
humanDate: { type: Date, required: false },
darwin: [
{
d: {
type: Array,
required: false
}
}
]
});
module.exports = mongoose.model('data', dataSchema);

我需要一个字符串列表在"d",我试试这个

db.getCollection('data').find({date:0},{'darwin.d.$': 1})

但是我有这个错误

Error: error: {
"operationTime" : Timestamp(1635348468, 1),
"ok" : 0,
"errmsg" : "positional operator '.$' couldn't find a matching element in the array",
"code" : 51246,
"codeName" : "Location51246",
"$clusterTime" : {
"clusterTime" : Timestamp(1635348468, 1),
"signature" : {
"hash" : BinData(0,"pfgMUIJkpgjlfnQ6cfiEDpSY+3o="),
"keyId" : NumberLong("7020434099001098244")
}
}}

我已经尝试了几件事,但我不能得到它的字符串列表,我不知道如果我应用'$'操作符错误

我预料会有这样的结果

{
date: 0,
darwin: [
{
d: 'string1'
},
{
d: 'string2'
},
{
d: 'string3'
}
]
}

可以这样使用聚合方法:

  • 第一个$match,其中date具有所需值
  • 然后$project映射到数组并获得您想要的值:对于darwin数组中的每个元素,使用$arrayElemAt获得d数组中的第一个元素。
db.collection.aggregate([
{
"$match": {
"date": 0
}
},
{
"$project": {
"_id": 0,
"date": 1,
"darwin": {
"$map": {
"input": "$darwin",
"as": "m",
"in": {
"d": {
"$arrayElemAt": [
"$$m.d",
0
]
}
}
}
}
}
}
])

哪个输出是:

[
{
"darwin": [
{
"d": "string1"
},
{
"d": "string2"
},
{
"d": "string3"
}
],
"date": 0
}
]

例子

最新更新