Home:ALL Converter>how to test each element of array in mongodb subdocument

how to test each element of array in mongodb subdocument

Ask Time:2019-09-17T17:58:13         Author:user123987

Json Formatter

I have mongodb document with the following data:

    amenities[
{
    amenity_id:52,
    Amenity:"AC"
},
{
    amenity_id:23,
    Amenity:"Free Parking"
}
]

I want to match each amenity_id element of the array with particular value and return true or false using condition $cond. I used

"$project":{'Free Parking':{'$cond':{'if':{'$in':['amenities.amenityId',[23]]},'then':'True','else':'False'}}

If a document contains amenity_id= 52 then a query has to return False. It is returning false irrespective of the menityId. The amenity Id could be list hence using $in. How can i test each element ?

Author:user123987,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57971814/how-to-test-each-element-of-array-in-mongodb-subdocument
sushant mehta :

Considering your input collection is\n\n[\n {\n amenities: [\n {\n _id: 52,\n Amenity: \"AC\"\n },\n {\n _id: 23,\n Amenity: \"Free Parking\"\n }\n ]\n }\n]\n\n\nusing aggregate pipeline $map \n\ndb.collection.aggregate([\n {\n $project: {\n amenites: {\n $map: {\n input: \"$amenities\",\n as: \"item\",\n in: {\n Amenity: \"$$item.Amenity\",\n _id: \"$$item._id\",\n isValid: {\n $cond: {\n if: {\n $eq: [\n \"$$item._id\",\n 23\n ]\n },\n then: true,\n else: false\n },\n\n }\n }\n }\n }\n }\n }\n])\n\n\nYou'll get result as:\n\n[\n {\n \"amenites\": [\n {\n \"Amenity\": \"AC\",\n \"_id\": 52,\n \"isValid\": false\n },\n {\n \"Amenity\": \"Free Parking\",\n \"_id\": 23,\n \"isValid\": true\n }\n ]\n }\n]\n",
2019-09-17T10:03:35
yy