考虑一个包含文档的集合(虚拟值如下所述):
{
id: "001",
company: "abc",
empDet: [
{
disableFlag: true,
name: 'raj',
age: 45,
designation: 'clerk'
},
{
disableFlag: false,
name: 'ramya',
age: 35,
designation: 'manager'
},
{
disableFlag: false,
name: 'gabriel',
age: 41,
designation: 'asstManager'
},
{
disableFlag: true,
name: 'saran',
age: 55,
designation: 'attender'
},
{
disableFlag: true,
name: 'buela',
age: 25,
designation: 'cashier'
}
],
location: "delhi"
},
{
id: "002",
company: "xyz",
empDet: [
{
disableFlag: true,
name: 'ravi',
age: 45,
designation: 'consultant'
},
{
disableFlag: true,
name: 'reka',
age: 35,
designation: 'manager'
},
{
disableFlag: false,
name: 'geetha',
age: 41,
designation: 'asstManager'
},
{
disableFlag: false,
name: 'varun',
age: 55,
designation: 'attender'
},
{
disableFlag: true,
name: 'balu',
age: 25,
designation: 'clerk'
}
],
location: "mumbai"
},
{
id: "003",
company: "pqr",
empDet: [
{
disableFlag: true,
name: 'bobby',
age: 45,
designation: 'consultant'
},
{
disableFlag: true,
name: 'vinay',
age: 35,
designation: 'manager'
},
{
disableFlag: true,
name: 'faritha',
age: 41,
designation: 'asstManager'
},
{
disableFlag: false,
name: 'arun',
age: 55,
designation: 'attender'
},
{
disableFlag: true,
name: 'kayal',
age: 25,
designation: 'clerk'
},
],
location: "calcutta"
}
使用node.js和mongoose,我想检索xyz
公司详细信息,但"empDet"
的值应该只包含disableFlag
的值为true。例如,我期望的输出应该是:
{
id: "002",
company: "xyz",
empDet: [
{
disableFlag: true,
name: 'ravi',
age: 45,
designation: 'consultant'
},
{
disableFlag: true,
name: 'reka',
age: 35,
designation: 'manager'
},
{
disableFlag: true,
name: 'balu',
age: 25,
designation: 'clerk'
}
],
location: "mumbai"
}
如何通过使用node.js和mongoose消除具有某些标志为false的数组对象值来查找或检索集合中的文档?
答案 0 :(得分:1)
在这种情况下, $redact
中的 aggregation framework 管道运营商应该适合您。这将以递归方式下降到文档结构中,并根据每个级别的指定条件的评估执行一些操作。这个概念可能有点棘手,但下面的例子证明了这一点:
Model.aggregate([
{
"$match": { "company" : "xyz" }
},
{
"$redact": {
"$cond": {
"if": {
"$eq": [ "$disableFlag", false ]
},
"then": "$$PRUNE",
"else": "$$DESCEND"
}
}
}
]).exec(function (err, results){
// handle error
console.log(results);
});
示例输出:
/* 0 */
{
"result" : [
{
"_id" : ObjectId("562e1398bf03613b4ad1b541"),
"id" : "002",
"company" : "xyz",
"empDet" : [
{
"disableFlag" : true,
"name" : "ravi",
"age" : 45,
"designation" : "consultant"
},
{
"disableFlag" : true,
"name" : "reka",
"age" : 35,
"designation" : "manager"
},
{
"disableFlag" : true,
"name" : "balu",
"age" : 25,
"designation" : "clerk"
}
],
"location" : "mumbai"
}
],
"ok" : 1
}
- 更新 - 如果您想填充属于xyz公司的员工的员工详细信息,您可以使用 populate 和最新版本的mongoose,它可以在查询中递归填充相关文档。已被添加。但这需要第二个查询,并使用不同的填充方式:
var pipeline = [
{
"$match": { "company" : "xyz" }
},
{
"$redact": {
"$cond": {
"if": {
"$eq": [ "$disableFlag", false ]
},
"then": "$$PRUNE",
"else": "$$DESCEND"
}
}
}
];
Model.aggregate(pipeline,
function(err, results) {
if (err) throw err;
Model.populate(results, {"path": "empDet.emp_id"}, function(err, results) {
if (err) throw err;
console.log(JSON.stringify(results, undefined, 4));
});
}
);