[英]MongoDB Aggregate Regex Match or Full Text Search returns whole Document
[英]Returns the whole document in find query - Mongodb
假设我的文档为;
{
id: 1,
name: "alex",
adress: [
{type: "home" , street: "flower"},
{type: "business" , street: "falls"},
{type: "xxx" , street: "xxx"},
]
}
我想home
。 为了得到这个,我编写了以下查询;
db.collection.find({id: 1, "adress.type" : "home"})
查询结果返回了我;
{
id: 1,
name: "alex",
adress: [
{type: "home" , street: "flower"},
{type: "business" , street: "falls"},
{type: "xxx" , street: "xxx"},
]
}
但是,我要的只是获得home adress
;
{
id: 1,
name: "alex",
adress: [
{type: "home" , street: "flower"}
]
}
如何缩小此查询的结果? 我应该如何编写查询以仅获取home adress
?
答案不适用于以下情况;
{
id: 1,
name: "alex",
adress: [
{type: "home" , street: "flower"},
{type: "business" , street: "falls"},
{type: "home" , street: "instinct"},
{type: "xxx" , street: "xxx"},
]
}
db.collection.find({id: 1, "adress.type" : "home"}, {"adress.$":1})
返回;
{
id: 1
"adress" : [
{
"type" : "home",
"street" : "flower"
}
]
}
这是不对的。 只有一场比赛。
我期望什么?
{
"id" : 1,
"name" : "alex",
"adress" : [
{
"type" : "home",
"street" : "flower"
},
{
"type" : "home",
"street" : "instinct"
}
]
}
因此问题仍然有效。 如何仅在mongodb find查询中找到匹配的部分?
您可以使用位置$运算符将查询结果中的数组内容限制为仅包含与查询文档匹配的第一个元素,如下所示:
db.collection.find({id: 1, "adress.type" : "home"}, {"name":1, "address.$":1});
但是,当您在选定文档中只需要一个特定的数组元素时,请在find()方法或findOne()方法的投影文档中使用$ 。
要获取数组中所有匹配的元素,而不仅仅是第一个元素,可以使用$ filter aggregator进行如下操作:
这是Mongodb 3.2版的新功能。
[{
"$match": {
"address.type": "home"
}
},
{
"$project": {
"address": {
"$filter": {
"input": "$address",
"as": "address",
"cond": {
"$eq": ["$$address.type", "home"]
}
}
}
}
}]
尝试聚合匹配并投影地址。
db.collection.aggregate([
{ $match : {id: 1, "adress.type" : "home"}},
{$project : { adress: 1} }
]}.exec(function (err, doc) {
if (err) callback(err);
else callback(null, doc);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.