MongoDB:检查嵌套数组是否包含子数组

编程入门 行业动态 更新时间:2024-10-24 23:28:40
本文介绍了MongoDB:检查嵌套数组是否包含子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用例,其中数据库的建模如下:

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:检查嵌套数组是否包含子数组

本文发布于:2023-11-22 15:14:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   嵌套   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!