我有這個資料結構:
{
date: 0,
darwin: [
{
d: ['string1', 1, 0, 0, 0]
},
{
d: ['string2', 1, 0, 0, 0]
},
{
d: ['string3', 1, 0, 0, 0]
}
]
}
和這個架構:
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'
}
]
}
uj5u.com熱心網友回復:
您可以使用這樣的聚合方法:
- 首先
$match是date具有所需值的檔案 - 然后
$project映射陣列并獲取您想要的值:對于darwin陣列中的每個元素,d使用$arrayElemAt.
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
}
]
示例在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340255.html
標籤:javascript 节点.js 数组 MongoDB 猫鼬
