我是mongo/mongoose(使用版本3.4.0)的新手,我想编写一个查询,返回与给定条件匹配的文档JSON数组的子集。 我的文档模型包含JSON数组,我希望查询只返回数组中匹配发生的记录,并且只返回特定的字段。Mongoose查询嵌套json数组,返回选定的字段
下面是一个例子模式:
Var testSchema = Schema({
name: { type: String },
bag: { type: Array} // JSON row data, containing fields name, phone, etc...
});
示例数据:
name: "alpha",
bag: [
{ item:"apple", color:"red", size:"small"},
{ item:"pear", color:"white", size:"small"},
{ item:"apple", color:"green", size:"large"}
]
name: "beta",
bag: [
{ item:"apple", color:"brown", size:"small"},
{ item:"pear", color:"white", size:"small"},
{ item:"apple", color:"green", size:"medium"}
]
或者
db.tests.insert({name:'alpha', bag:[{ item:'apple', color:'red', size:'small'},{ item:'pear', color:'white', size:'small'},{ item:'apple', color:'green', size:'large'}]})
db.tests.insert({name:'beta', bag:[{ item:'apple', color:'brown', size:'small'},{ item:'pear', color:'white', size:'small'},{ item:'apple', color:'green', size:'medium'}]})
我希望能够查询这个数据,但只返回“bag”数据与查询条目“apple”相匹配,只返回“bag”中的“item”和“color”字段。
Name: "alpha", bag: [{ item: "apple", color: "red" }, { item: "apple", color: "green" }]
Name: "beta", bag: [{ item: "apple", color: "brown" }, { item: "apple", color: "green" }]
我已经使用聚合与匹配和项目的尝试:
db.tests.aggregate([
{"$match":{"bag.item":"apple"}},
{"$project":{
"Bag.item":{
"$filter":{
"input":"$bag",
"As":"bag",
"cond":{"$eq":["$$bag.item", "apple"]}
}},
"Bag.color":1
}}]);
但这返回色域的所有项目,而不仅仅是苹果,仍然返回该尺寸领域。
我看到这些:
Mongodb Trying to get selected fields to return from aggregate
Retrieve only the queried element in an object array in MongoDB collection
,但仍然没有想出如何限制嵌套的JSON数组中的项目。
什么是您的mongodb服务器版本? – Veeram
db.version()是3.4.0 – J21042