Reputation: 31
I have an array of JSON objects which represent sales that a user wants to receive notifications about, and each JSON object in the array has an itemName and a maxPriceDesired field.
I have a separate collection of sales to notify users with, and each sale has an itemName, price, and location field.
What I want is to return each sale object if and only if the sales itemName is in the user's list of items they want to receive notifications about and that sales price is less than or equal to the maxDesiredPrice. I can't figure out how to query so that I get this. For example, say that a user has this JSON array for his or her interests:
[
{ itemName: MacBook Pro, maxDesiredPrice: 1000.00},
{ itemName: iPhone 6, maxDesiredPrice: 800 }
]
And the sales collection has
[
{ itemName: MacBook Pro, price: 1250.00 },
{ itemName: iPhone 6, price: 700.00 }
]
Then I want to return only the iPhone 6 sale in the query, because the user has expressed interest in the item (matching the itemName) and its price is less than the max desired price.
Upvotes: 0
Views: 359
Reputation: 151132
So given the data already retrieved from the "user" into a user
variable where the items are expressed in an "interested_in" property:
{
"interested_in": [
{ "itemName": "MacBook Pro", "maxDesiredPrice": 1000.00 },
{ "itemName": "iPhone 6", "maxDesiredPrice": 800 }
]
}
Then you would use the information in an $or
query expression with some modification like so:
var interested = user.interested_in.map(function(item) {
item.price = { "$lte": item.maxDesiredPrice };
delete item.maxDesiredPrice;
return item;
});
db.sales.find({ "$or": interested })
Or basically some process to manipulate the keys into the desired form to issue the query in whatever language you are actually using. The principle remains the same.
Upvotes: 1