php - Mongo - Array query, only find where all elements match -
i'm trying create mongo query return results arrays have specific element set false.
an example data record :-
images: [ { id: objectid("516bef7fc05e877b31000000"), primary: true }, { id: objectid("516bef2ac05e879622000000"), primary: false }, { id: objectid("516beeb7c05e879e2a000000"), primary: false } ], name: "test", etc: "etc"
i wish find documents primary fields set false (using no query selectors or elemmatch) mongo return document because @ least 1 of array elements match.
how make mongo return documents match search parameters?
many thanks.
you can aggregation framework quite easily:
db.so.aggregate( [ { $unwind: "$images" }, { $group: { _id: '$_id', all: { $sum: 1 }, all_primary: { $sum: { $cond: [ { $eq: [ '$images.primary', true ] }, 1, 0 ] } }, images: { $push: '$images' }, name: { $first: '$name' }, etc: { $first: '$etc' }, } }, { $project: { _id: 1, images: 1, name: 1, etc: 1, same: { $cond: [ { $eq: [ '$all', '$all_primary' ] }, 1, 0 ] } } }, { $match: { 'same' : 1 } } ] );
with input:
{ "_id" : objectid("5203730bf8eaa52a846ebc3e"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000010"), "primary" : true } ], "name" : "derick", "etc" : true } { "_id" : objectid("52037315f8eaa52a846ebc3f"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000020"), "primary" : false } ], "name" : "james", "etc" : true } { "_id" : objectid("520373621a78238235b6ffbf"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000020"), "primary" : false } ], "name" : "james", "etc" : true } { "_id" : objectid("5203736b1a78238235b6ffc0"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000020"), "primary" : true } ], "name" : "james", "etc" : true }
this outputs:
{ "result" : [ { "_id" : objectid("5203736b1a78238235b6ffc0"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000020"), "primary" : true } ], "name" : "james", "etc" : true, "same" : 1 }, { "_id" : objectid("5203730bf8eaa52a846ebc3e"), "images" : [ { "id" : objectid("516bef7fc05e877b31000000"), "primary" : true }, { "id" : objectid("516bef2ac05e879622010000"), "primary" : true }, { "id" : objectid("516beeb7c05e879e2a000010"), "primary" : true } ], "name" : "derick", "etc" : null, "same" : 1 } ], "ok" : 1 }
Comments
Post a Comment