大佬教程收集整理的这篇文章主要介绍了MongoDB 聚合:如何确定一个数组是否包含多个元素,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下数据。
[
{
"_ID": 1,"array": [
{
"name": "name1","nestedArray": [
{
"key": "key1","value": "value1"
},{
"key": "key2","value": "value2"
}
]
},{
"name": "name2","value": "abc"
},"value": "value2"
}
]
}
]
}
]
playground 我想保留其nestedArray 包含2 个匹配元素的条目并删除其他元素。 2个元素在下面
{
"key": "key1","value": "abc"
},{
"key": "key2","value": "value2"
}
这样结果就会低于
[
{
"_ID": 1,"array": [
{
"name": "name2","value": "value2"
}
]
}
]
}
]
name
="name1" 被删除的那个,因为它只有一个匹配的元素。
感觉我们可以使用 $elemmatch
但无法弄清楚。
首先,放松 array
,以便您可以轻松访问 nestedArray
。
其次,在 nestedArray
上使用 $all 和 $elementMatch
db.collection.aggregate([
{
$unwind: "$array"
},{
$match: {
"array.nestedArray": {
$all: [
{
"$elemMatch": {
key: "key1",value: "abc"
}
},{
"$elemMatch": {
key: "key2",value: "value2"
}
}
]
}
}
},{
$group: {
_id: "$_id",array: {
"$push": "$array"
}
}
}
])
playground
,您并未真正指定输入的外观,但无论如何策略将保持不变,我们将使用 $filter 迭代数组并仅匹配其 subarray
大小相等的文档到基于给定输入的过滤子数组,如下所示:
// the current input structure.
inputArray = [
{
"key": "key1","value": "abc"
},{
"key": "key2","value": "value2"
}
];
db.collection.aggregate([
{
$project: {
array: {
$filter: {
input: "$array",as: "element",cond: {
$and: [
{
$eq: [
{
$size: {
$filter: {
input: "$$element.nestedArray",as: "nested",cond: {
"$setIsSubset": [
[
"$$nested"
],inputArray
]
}
}
},},{
$size: "$$element.nestedArray"
}
]
},{ // this is required for an exact match otherwise subsets are possible,if you wan't to allow it delete this equality completly.
$eq: [
{
$size: "$$element.nestedArray"
},{
$size: inputArray
}
]
}
]
}
}
}
}
}
])
同样,如果输入采用不同的结构,您必须更改 $eq
条件
以上是大佬教程为你收集整理的MongoDB 聚合:如何确定一个数组是否包含多个元素全部内容,希望文章能够帮你解决MongoDB 聚合:如何确定一个数组是否包含多个元素所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。