Search code examples
mongodbmongodb-javamongo-javamongo-jackson-mappermongojack

compare two collections in mongodb using java or an simple query


I am having following document (Json) of an gallery,


    {
        "_id": "53698b6092x3875407fefe7c",
        "status": "active",
        "colors": [
            "red",
            "green"
        ],
        "paintings": [
            {
                "name": "MonaLisa",
                "by": "LeonardodaVinci"
            },
            {
                "name": "JungleArc",
                "by": "RayBurggraf"
            }
        ]
    }

Now I am also having one collection of colors say
COLORS-COLLECTION: ["black","yellow","red","green","blue","pink"]
I want to fetch paintings by it's name matching to provided text say "MonaLisa" (as search query) also I want to compare two colors with COLORS-COLLECTION, if colors has any of the matching color in COLORS-COLLECTION then it should return the painting.
I want something like below:

 

    {
        "paintings": [
            {
                "name": "MonaLisa",
                "by": "LeonardodaVinci"
            }
        ]
    }

Please help me!!. Thanks in advance.


Solution

  • If I get you correctly, aggregation framework would do your job:

    db.gallery.aggregate([
        {"$unwind": "$paintings"},
        {"$match": {"paintings.name": 'MonaLisa', "colors": {"$in": ["black","yellow","red","green","blue","pink"]}}},
        {"$project": {"paintings": 1, "_id": 0}}
    ]);