2017-08-17 453 views
1

檢索子文檔我有蒙戈集合在我的數據庫:如何貓鼬

[ 
    { 
     "_id": "59955bb0cd522a00bcaab08c", 
     "lang": "en", 
     "__v": 0, 
     "message_subsets": [ 
      { 
       "identifier": "errors", 
       "_id": "59955bb0cd522a00bcaab08d", 
       "messages": [ 
        { 
         "identifier": "invalid", 
         "message_text": "$FIELD$ is invalid", 
         "_id": "59955bb0cd522a00bcaab091" 
        }, 
        { 
         "identifier": "empty", 
         "message_text": "$FIELD$ is required", 
         "_id": "59955bb0cd522a00bcaab090" 
        } 
       ] 
      } 
     ] 
    }, 
    { 
     "_id": "59955bb0cd522a00bcaab08c", 
     "lang": "ru", 
    ... 
] 

這是由這個貓鼬架構構建:

const MessageSchema = new mongoose.Schema({ 
    identifier: { 
     type: String, 
     unique: true, 
     required: true, 
     trim: true 
    }, 
    message_text: { 
     type: String, 
     required: true, 
     trim: true 
    } 
}); 

const MessageSubsetSchema = new mongoose.Schema({ 
    identifier: { 
     type: String, 
     unique: true, 
     required: true, 
     trim: true 
    }, 
    messages: [MessageSchema] 
}); 

const LangMessageSetSchema = new mongoose.Schema({ 
    lang: { 
     type: String, 
     unique: true, 
     required: true, 
     trim: true 
    }, 
    message_subsets: [MessageSubsetSchema] 
}); 

我想從message_subsets陣列檢索所有messages如果其父母有"lang": "en",則爲"identifier": "errors"。 因爲我對貓鼬和蒙戈有點新,所以我堅持了!你能幫助我以正確的方式查詢數據嗎?謝謝。

回答

0

這應該工作:

Collection.find({'messages.message_subsets.identifier':'errors', 'lang': 'en'}, {'messages': 1}) 
+0

是所有messages到一個messages陣列,但不完全是。我想只檢索消息數組。 – bashkovpd

+0

@bashkovpd我已更新。它被稱爲投影:https://docs.mongodb.com/manual/reference/operator/projection/positional/ – Lazyexpert

+0

嗯...也許我做錯了,但該查詢只返回_id的主要父元素(其中'朗'指定)。 – bashkovpd

0

可以在3.4蒙戈服務器版本試試下面聚集。

下面的查詢將使用$filter收集所有地方identifier之後$let表達errormessage_subsets到項目中message_subsets所有匹配messages

$reduce運營商將合併($concatArrays)每配套文件

db.collection_name.aggregate(
[ 
    { 
    "$match": { 
     "lang": "en", "message_subsets.identifier":"errors" 
    } 
    }, 
    { 
    "$project": { 
     "messages": { 
     "$reduce": { 
      "input": { 
      "$let": { 
       "vars": { 
       "message_s": { 
        "$filter": { 
        "input": "$message_subsets", 
        "as": "message_s", 
        "cond": { 
         "$eq": [ 
         "$$message_s.identifier", 
         "errors" 
         ] 
        } 
        } 
       } 
       }, 
       "in": "$$message_s.messages" 
      } 
      }, 
      "initialValue": [], 
      "in": { 
      "$concatArrays": [ 
       "$$value", 
       "$$this" 
      ] 
      } 
     } 
     } 
    } 
    } 
])