0

For example, I have these documents in my collection.

{
   _id: ObjectId("5234cc89687ea597eabee675"),
   code: "xyz",
   tags: [ "school", "book", "bag", "headphone", "appliance" ],
   qty: [
      { size: "S", num: 10, color: "blue" },
      { size: "M", num: 45, color: "blue" },
      { size: "L", num: 100, color: "green" }
    ]
}

{
   _id: ObjectId("5234ccb7687ea597eabee677"),
   code: "efg",
   tags: [ "school", "book" ],
   qty: [
      { size: "S", num: 10, color: "blue" },
      { size: "S", num: 100, color: "blue" },
      { size: "S", num: 100, color: "green" }
    ]
}

I want to get the second document, every 'size' is 'S'.
I have tried $all and $elemMatch
(like this: https://docs.mongodb.com/manual/reference/operator/query/all/#use-all-to-match-values), but it still return me both of them. Is there any other way to do this?
I know I can use $aggregate with $unwind, $project... to make it, but if I want to update it, what should I do. I just want to find(update) the document that all 'size' in its 'qty' are 'S', not some of them are 'S'.

ip192
  • 149
  • 1
  • 8
  • What does your query that "still return both of them" look like? – Davis Molinari Jul 06 '17 at 08:21
  • 1
    @neil-lunn : Looks like the duplicate stack overflow quition taged for this one is not the exact solution to current one. I think, user wants to return all the documents where all quantity are of small size – Manoj Shevate Jul 06 '17 at 08:24
  • @ManojShevate Go and look and count how many answers mention `$filter`. Duplicate. We get a couple of the same thing almost every day. – Neil Lunn Jul 06 '17 at 08:29
  • @NeilLunn how can the $filter operator be used to express the logic to retrieve "just documents where ALL qty have size S"? The first doc here shouldn't be retrieved because it has qty with size different from 'S' – Davis Molinari Jul 06 '17 at 09:08
  • 2
    confused with the answers in the duplicate question link. here is query which can be used db.collectionName.find({qty: {$not: {$elemMatch: {"size": {$nin: ["S"]}}}}}) – Manoj Shevate Jul 06 '17 at 09:31
  • I know I can use $aggregate and $unwind, $project... to make it, but if I want to update it, what should I do. I just want to find(update) the document that all 'size' in its 'qty' are 'S'. – ip192 Jul 06 '17 at 10:14
  • I tried your way and it's fit me, thank you@Manoj Shevate – ip192 Jul 13 '17 at 11:52

0 Answers0