'using $and with $match in mongodb
I am trying to use the following query in MongoDB but it is not working.
db.test.aggregate(
$match: {$and: [type: {$in: ["TOYS"]}, type: {$nin: ["BARBIE"]}, time:
{$lt:ISODate("2013-12-09T00:00:00Z")}]}})
It says invalid character ":".
Is it possible to use $and with $match? I have seen an example on this forum of $or with $match so I presumed this is possible.
Thank you in advance for your help and guidance.
Solution 1:[1]
db.test.find( {$and: [ {"type": {$in: ["TOYS"]}},
{"type": {$nin: ["BARBIE"]}},
{"time": {$lt:ISODate("2013-12-09T00:00:00Z")}}
]
})
AND works with FIND, receives an array of matches (but it's not a match instruction) Aggregation framework is for something completely different, it's like the word says, for aggregating (count, sum, avg, and so worth grouping or unwinding, etc)
Solution 2:[2]
{
$match: {
$or:[
{'sender':sender, 'recipient':recipient},
{'recipient':sender,'sender':recipient}
]
}
}
using $or
Solution 3:[3]
example of $lookup then $match
db.orders.aggregate([
{
"$lookup": {
"from": "user",
"localField": "user",
"foreignField": "_id",
"as": "user"
}
},
{
"$unwind": "$user"
},
{
"$match": {
"$and": [
{
"privacy.mode": {
"$gt": 0
}
},
{
"user.privacy.mode": {
"$gt": 0
}
}
]
}
}
])
``
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KOGI |
| Solution 2 | alfonsoolavarria |
| Solution 3 | Rafiq |
