如何编写查询条件的一些对象不能在对象数组和其他对象之一必须在对象数组?
我有学生收集如下的mongo文件:
{ name: 'XYZ', age: 26, education: [ { title: 'abc', university: 'pqr', grade: 'A' }, { title: 'def', university: 'uvq', grade: 'B' }, { title: 'ghi', university: 'xyz', grade: 'A' }, { title: 'jkl', university: 'pqr', grade: 'B' }, { title: 'mno', university: 'uvw', grade: 'C' } ] }, { name: 'QQQ', age: 26, education: [ { title: 'abc', university: 'pqr', grade: 'A' }, { title: 'ghi', university: 'xyz', grade: 'A' }, { title: 'jkl', university: 'xyz', grade: 'B' }, { title: 'mno', university: 'pqr', grade: 'C' } ] }
现在我想写一个查询,我想要学生必须完成他们的
{education-title:'abc' with grade A}
或{education-title:'def' with grade B}
但不能完成
{education-title:'jkl' with university:pqr}
AND{education-title:'mno' with university:uvw}
如果仔细观察我的文档name: QQQ
满足所有条件,应该是查询的输出。 我试图通过在$elemMatch
运算符中使用$or
$and
$elemMatch
符来解决这些问题,但不确定我的方法是否正确。 我的查询如下所示
studentModel.aggregate({ { $match: { 'education': $elemMatch: { $or: [{ 'title': 'abc', 'grade': 'A' }, { 'title': 'def', 'grade': 'B' } ]}, $not: { $elemMatch: { $and: [{ 'title': 'jkl', 'university': 'pqr' }, { 'title': 'mno', 'university': 'uvw' } ] } } } });
上面的代码工作,给我的输出,但我不知道它是否会与数百万logging,仍然产生预期的输出或不。 我只是想确定,如果我在$ elemMatch中使用$和AND $或运算符的方法是正确的?
当我运行你的查询时,它错误地select了第一个文档,这是因为$not
的第二个条件实际上不能匹配一个元素,因为$elemMatch
不可能为同一个属性包含“multiple conditions” 元素 。 这就是$elemMatch
在“在同一个数组元素上匹配多个条件”的区别。 因此命名。
正确的方法是列出“单独的” $elemMatch
语句,并用$all
包装它们:
db.getCollection('students').find({ "education": { "$elemMatch": { "$or": [ { "title": "abc", "grade": "A" }, { "title": "def", "grade": "B" } ] }, "$not": { "$all": [ { "$elemMatch": { "title": "jkl", "university": "pqr" }}, { "$elemMatch": { "title": "mno", "university": "uvw" }} ] } } })
这正确地只从提供的样品中select第二个QQQ
文件。