我有一个用例,其中数据库的建模如下:
I have a use case where the database is modelled like this:
name: XYZ gradeCards: [{ id: 1234, // id of the report card comments: ['GOOD','NICE','WOW'] }, { id: 2345, comments: ['GOOD','NICE TRY'] }]现在,我有一个查询,我想按如下方式查询架构:
Now, I have a query that I would like to query the schema as follows:
我将获得ID和值的列表. 例如:给定的列表如下:
I would be given a list of ids and values. For example: the given list is as follows:
[{ id: 1234, comments: ['GOOD','NICE'] },{ id: 2345, comments: ['GOOD'] }]简而言之,ID应该匹配,并且注释应该是该ID的注释数组的子数组,而且,数组中指定的所有条件都应该匹配,因此在所有条件.
In short the ID should be matching and the comments should be a sub-array of the comments array for that id and also, all the conditions specified in the array should be matched, so it should be an AND condition on all the conditions provided.
我能够进入此查询,但是它与comments数组中的所有元素都匹配,我希望ID应该完全匹配,并且注释应该是子数组.
I was able to get to this query, but it matches all of the elements in the comments array, I want that id should be exactly matched and comments should be a subarray.
用于匹配注释数组中的所有元素:
For matching all elements in comments array:
db.getCollection('user').find({arr:{ $all: [{ id:1234, comments:['GOOD','NICE','WOW'] },{ id:2345, comments:['GOOD','NICE TRY'] }] }})推荐答案
您可以尝试使用$all和$elemMatch来匹配查询条件.
You can try $all with $elemMatch to match on the query conditions.
db.collection.find({ gradeCards: { $all: [{ "$elemMatch": { id: 1234, comments: { $in: ['GOOD', 'NICE'] } } }, { "$elemMatch": { id: 2345, comments: { $in: ['GOOD'] } } }, ] } })更多推荐
MongoDB:检查嵌套数组是否包含子数组
发布评论