4

I have a mongo document collection like the following, I'm trying to find the documents which has images for all the colors in that document also the document template should not be empty.

[
    {
        "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 : []
            }
        ]  
    }
]

I tried the following query but it's not working.

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

What I can do to get something like that?

Unnikrishnan
  • 2,683
  • 5
  • 22
  • 39

1 Answers1

2

here you go...

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

see it working here: https://mongoplayground.net/p/ylkdo9AAmZL

here's the c# counterpart for anybody interested:

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();
        }
    }
}
Dĵ ΝιΓΞΗΛψΚ
  • 5,068
  • 3
  • 13
  • 26