using $and with $match in mongodb

2019-01-21 20:18发布

问题:

I am trying to use the following query in MongoDB but it is not running.

db.test.aggergate(
$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.

回答1:

$and with $match works just fine.

You have syntax errors in your query. Try this.

db.test.aggregate([
                   { 
                     $match: {
                          $and: [ 
                              {type: {$in: ["TOYS"]}}, 
                              {type: {$nin: ["BARBIE"]}}, 
                              {time: {$lt:ISODate("2013-12-09T00:00:00Z")}}
                          ]
                     }
                   }
                  ])

And for what you are trying to do, you do not need an $and.



回答2:

If anybody wants to refuse my answer it's ok, this is a typical question with lack of research

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)



回答3:

{
  $match: {
    $or:[
      {'sender':sender, 'recipient':recipient},
      {'recipient':sender,'sender':recipient}
    ]
  }
}

using $or



回答4:

Below is how i am doing with many $and along with $or

User.aggregate([
 {
  $lookup:{
   from:'influencers',
   localField:'_id',
   foreignField:'user',
   as:'influencer'
 }
 },
 { $match:{ '$and': 
  [ { '$and': [ { 'influencer.aboutMe.birthday': { '$lte': 2017-09-11T09:10:07.283Z } } ] },
  { '$and': [ { 'influencer.aboutMe.minPrice': { '$gte': 0 } } ] },
   { '$and': 
    [ { '$or': 
        [ { '$and': [ { 'influencer.followed_by': { '$gte': 0 } } ] },

         { '$and': [ { 'influencer.youTubeSubscribercount': { '$gte': 
  0 } } ] } ] } ] },
 { 'influencer.isAdminverified': true },
 { 'influencer.status': 'Verified' } ] } }

]);


标签: mongodb match