mongodb - 如何在 MongoDB 的项目数组中查找包含非空数组的文档

标签 mongodb nosql

我有一个如下所示的 mongo 文档集合,我正在尝试查找包含该文档中所有颜色图像的文档,而且文档模板不应为空。

[
    {
        "template" : "one",
        "colors" : [
            { 
                "name" : "yellow",
                images : ["img_one", "image_two"]
            },
            { 
                "name" : "blue",
                images : ["img_one", "image_two"]
            }
        ]
    },
    {
        "template" : "",
        "colors" : [
            { 
                "name" : "green",
                images : ["img_one", "image_two"]
            },
            { 
                "name" : "orange",
                images : ["img_one", "image_two"]
            }
        ]      
    },
    {
        "template" : "three",
        "colors" : [
            { 
                "name" : "green",
                images : ["img_one", "image_two"]
            },
            { 
                "name" : "orange",
                images : []
            }
        ]  
    }
]

我尝试了以下查询,但它不起作用。

db.getCollection('my_products').find({
    "template": {$ne : ""},
    "colors": {
        $all: [
            {
                "$elemMatch": {"images": {$not : {$size : 0}}}
            }
        ]
    }
});

我该怎么做才能得到这样的东西?

最佳答案

给你...

db.my_products.aggregate([
    {
        "$match": {
            "template": {
                "$ne": ""
            },
            "colors": {
                "$not": {
                    "$elemMatch": {
                        "images": {
                            "$size": 0
                        }
                    }
                }
            }
        }
    }
])

看到它在这里工作:https://mongoplayground.net/p/ylkdo9AAmZL

这是任何感兴趣的人的 c# 副本:

using MongoDB.Entities;
using System.Linq;

namespace StackOverflow
{
    public class Program
    {
        public class product : Entity
        {
            public string template { get; set; }
            public color[] colors { get; set; }
        }

        public class color
        {
            public string name { get; set; }
            public string[] images { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test");

            var result = DB.Queryable<product>()
                           .Where(p =>
                                  p.template != "" &&
                                  !p.colors.Any(c => c.images.Count() == 0))
                           .ToList();
        }
    }
}

关于mongodb - 如何在 MongoDB 的项目数组中查找包含非空数组的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57287064/

相关文章:

json - 如何将 JSON 数组保存到 mongodb 集合中

javascript - 如何在没有 MongoLab 的情况下将本地 MongoDB 数据库连接到我的 Android Studio 应用程序?

javascript - MongoDb shell 脚本

sql - 如何选择数据库?

node.js - Mongoose startSession() 挂起

javascript - 服务器上的 Express cookie 不等于客户端

Node.js module.exports 函数从 MongoDB 返回数组

javascript - MongoDB - 仅在嵌套数组中存在时更新所有条目

java - NoSql 之战——幸存者?

javascript - NOSQL 数据库存储和组织图像的最佳位置是什么