Get all results from an array that matches the property

I know how to get MongoDB to find a string based on such an array:

useritems.find({userid: useridhere,  "items.id": idhere})

But how could I, for example, search and retrieve all elements that are activated, or retrieve all elements based on a property items? Such as:

useritems.find({userid: useridhere,  "items.activated": true})

It will be the result of receiving all elements from the user where true is activated.

Here is my element diagram:

var userItemsSchema = new Schema({
    userid : String,
    items: [
        {
            id: {type: Number, default: 1},
            activated: { type: Boolean, default: false},
            endtime : {type: Number, default: 0},
        },
    ],
});

module.exports = mongoose.model('useritems', userItemsSchema);
+6
source share
3 answers

You want $filterhere:

useritems.aggregate([
  { "$match": { 
    "userid": ObjectId(useridhere),  
    "items.activated": true
  }},
  { "$addFields": {
    "items": {
      "$filter": {
        "input": "$items",
        "as": "i",
        "cond": "$$i.activated"
      }
    }
  }}
],(err,results) => { 

});

, , useridhere, mongoose "" " " ObjectId . № 1399, , "", , "".

, :

const ObjectId = require('mongodb').ObjectID;

"" .

, , req.params , ObjectId.

, .aggregate() , , " " - . :

useritems.find({ userid: useridhere,  "items.activated": true })
 .select('items.$')
 .exec((err,items) => {

 });

$ "" , - "" .

, "" , $filter, , MongoDB $unwind .

$unwind (Anything past MongoDB 2.4) "" , $group, " ". , , " ", $lookup, .

. $filter.

. $addFields "" . MongoDB , $project . :

  { "$project": {
    "userid": 1,
    "items": {
      "$filter": {
        "input": "$items",
        "as": "i",
        "cond": "$$i.activated"
      }
    }
  }}
+3

aggregate :

useritems.aggregate(
    { $match: {"_id" : id}},
    { $unwind: '$items'},
    { $match: {'items.activated': true}},
    { $group: {_id: '$_id', items: {$push: '$items'}}})

: MongoDB

+1

$elemMatch

, , , MongoDB.

    db.useritems.find({
    userid: "random user_id",
    items: {
        $elemMatch: {
            activated: true
        }
    }
 })
-1

All Articles