[英]Mongodb find array length greater than specified size
我有這個貓鼬模型架構
const postSchema = new Schema({
title: String,
headline: [{
kind: String,
id: Schema.Types.ObjectId,
content: String,
relevance: Number,
_id: false
}],
});
我想在數據庫中找到headline
數組長度大於 x 的模型
我有這個查詢:
const query = {
'headline.kind': 'topic',
'headline.id': topicId,
'headline':{
'$size':{
'$gt': x
}
}
};
但是當我使用它時,我得到:
{ MongooseError: Cast to number failed for value "{ '$gt': 2 }" at path "headline"
at CastError (/home/oleg/WebstormProjects/lectal/api/node_modules/mongoose/lib/error/cast.js:26:11)
有人知道構造這個查詢的正確方法嗎? (在我的代碼中,我只是硬編碼了 x 的數字 2。)
對於最有效的方法,您可以通過指定n
位置使用“點符號”來完成此操作。 這基本上是說如果一個數組“至少”有n + 1
元素,則返回它。
因此,與其編寫{ "$gt": 2 }
不如查找“第三個”元素的索引值的存在(從零索引第三個為 2 ):
{ "headline.2": { "$exists": true } }
$exists
運算符正在查找該給定索引處是否存在元素,當滿足條件時,數組必須至少具有該長度,因此“大於二”
另請注意,您的查詢條件想要匹配數組元素上的多個屬性,為此您實際上使用$elemMatch
,否則條件實際上適用於匹配數組中的任何元素,而不僅僅是具有“兩個”條件的元素為$elemMatch
確實如此。
{
"headline": { "$elemMatch": { "kind": "topic", "id": topicId } },
"headline.2": { "$exists": true }
}
要“動態地”做到這一點,我們只需構建從參數生成鍵的查詢:
const query = {
"headline": { "$elemMatch": { "kind": "topic", "id": topicId } }
};
query['headline.'+x] = { "$exists": true }
從我讀過的內容來看,使用$size
和$gt
是不可能的。
嘗試使用$where
- http://mongoosejs.com/docs/api.html#query_Query-%24where
$expr:{$gte: [{$size: "$preferredArray"}, specifiedsize]}
如果您使用聚合,它會更好更快; 整個查詢如下所示:
db.collection.aggregate([
{
$match: {
preferred criteria:1,
$expr:{$gte: [{$size: "$diagnosis"}, 2]}
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.