mongodb - Query Collection for Subsets -
trying query mongo collection documents subsets of object (query). e.g.
object: { "animal": "cat" ,"owner": "mike" ,"color": "blue" ,"city": "houston" } collection: [ [0]{ "color": "red" ,"animal": "cat" } [1]{ "color": "blue" } [2]{ "owner": "mike" ,"city": "houston" } ] result: [1]{ "color": "blue" } [2]{ "owner": "mike" ,"city": "houston" }
you need build query dynamically based on properties of javascript object.
the query like:
$and : [ {$or : [{ color: { $exists: true, $eq: 'blue' } }, {color: { $exists:false} }]}, {$or : [{ owner: { $exists: true, $eq: 'mike' } }, {owner: { $exists:false} }]}, ... // iterate through other properties. ]
edit:
using $and
means documents in collection have property must match object
- change $or
match of attributes.
edit 2
also worth considering performance poor large collections if don't use indexed attributes in query. 1 solution problem use array , multikey index.
i.e.
{ tags : [ "color=blue","owner=mike" ] }
this way can use regex \^color=\
return docs class= tag , use index. \^color=blue\ blues.
then multiple conditions use $all
or $in
operators.
e.g.
{ tags : { $in: [/^color=blue/, /^owner=mike/]} }
hope helps
Comments
Post a Comment