Query to retrieve multiple elements in an array

If I have the following payload:

{
    "objs": [
        {  "_id": "1234566", "some":"data", "key": "one" },
        {  "_id": "1234576", "some":"data", "key": "one" },
        {  "_id": "2345666", "some":"otherdata", "key": "two" },
        {  "_id": "4566666", "some":"yetotherdata", "key": "three" },
    ]
}

      

How can I return all objects (objs) with the following:

key:  "one"
_id: [1234566, 1234576]

      

thank

+3


source to share


2 answers


The query find()

returns all objs

that have supporting documents that match these conditions.

var input = ["1234566","1234576"];
db.collection.find({$and:[{"objs._id":{$in:input}},{"objs.key":"one"}]})

      

If you want to get the edited documents inside an array objs

, you can achieve this using aggregate pipeline operations.

  • Define a variable to hold the input values.
  • $unwind

    objs

    , this gives you separate documents for each element in the objs array.
  • $match

    only those documents that meet the selection criteria.
  • $group

    "_id"

    document with autogeneration mongo

    .
  • $project

    required fields.


Code:

var input = ["1234566","1234576"];
db.collection.aggregate([
{$unwind:"$objs"},
{$match:{"objs._id":{$in:input},"objs.key":"one"}},
{$group:{"_id":"_id","objs":{$push:"$objs"}}},
{$project:{"_id":0,"objs":1}}
])

      

o / r

{ "objs" : 
         [ { "_id" : "1234566", "some" : "data", "key" : "one" },
           { "_id" : "1234576", "some" : "data", "key" : "one" } ] }

      

+2


source


You can not. MongoDB returns a document matching the query conditions, not individual parts matching the query conditions. You can suppress or include fields of corresponding projected documents, but you cannot (since 2.6) return an array that is limited only to contain elements that meet the conditions for the array. You can only return the first such match with $

db.collection.find(
    { "objs" : { "$elemMatch" : { "_id" : { "$in" : [1234566, 1234576] }, "key" : "one" } } }, // query
    { "_id" : 0, "objs.$" : 1 } // projection
)

      



If you want to return all matching elements objs

, chances are you should make each subdocument in the array objs

into its own document in the collection.

+1


source







All Articles