我有一种情况,我想运行一个查询,该查询必须匹配某些字段条件,但应该匹配其他字段条件。但是,如果它们不匹配,查询仍然应该返回MUST的条件。
例如,假设在一个集合中,我有3个文档,例如:
{ _id: 1, position: “Developer”, name: “Greg”, surname: “Smith” },
{ _id: 2, position: “QA”, name: “Andrew”, surname: “Samson” },
{ _id: 3, position: “Developer”, name: “Adam”, surname: “Mount” }
如果我运行一个条件为{ position: “Developer” }
(必须(和{ name: “Greg” }
(应该(的查询,我应该只得到记录:
{ _id: 1, position: “Developer”, name: “Greg”, surname: “Smith” }
但是,如果我再次使用{ position: “Developer” }
和{ “name”: “Daniel” }
运行查询,我应该得到与MUST条件匹配的所有记录,因此如果不匹配,我不希望position
条件使查询失败。所以返回记录:
{ _id: 1, position: “Developer”, name: “Greg”, surname: “Smith” },
{ _id: 3, position: “Developer”, name: “Adam”, surname: “Mount” }
此外,如果我有一个具有MUST条件{ position: “Developer” }
和SHOULD条件{ name: “Greg”, surname: “Garbrandt” }
的查询,我仍然应该得到:
{ _id: 1, position: “Developer”, name: “Greg”, surname: “Smith” }
不确定是否有一种方法可以编写这样的查询,或者是否有一个功能可以直接做到这一点。
您可以使用这个:
var name = "Daniel";
db.collection.aggregate([
{ $match: { position: "Developer" } },
{
$match: {
$expr: {
$cond: {
if: db.collection.findOne({ position: "Developer", name: name }),
then: { $eq: ["$name", name] },
else: true
}
}
}
}
])
或者这个:
db.collection.aggregate([
{ $match: { position: "Developer" } },
{ $group: { _id: null, data: { $push: "$$ROOT" } } },
{ $set: { cond: { $filter: { input: "$data", cond: { $eq: ["$$this.name", "Daniel"] } } } } },
{
$project: {
data: {
$cond: {
if: { $eq: ["$cond", []] },
then: "$data",
else: "$cond"
}
}
}
},
{ $unwind: "$data" },
{ $replaceWith: "$data" }
])