0

I have 2 collections in mongoDB:

db.getCollection('orderTest').insert([
{"id":1,"code":"abc","atrub1":"value1","atrub2":"value2","atrub100":"value100g"},
{"id":2,"code":"abc","atrub1":"value11","atrub2":"value42","atrub100":"value100gr"},
{"id":3,"code":"efg","atrub1":"value111","atrub2":"value22","atrub100":"value100g45"},
{"id":4,"code":"fff","atrub1":"value123","atrub2":"valuer322","atrub100":"value100g45r"},
{"id":5,"code":"fff","atrub1":"value42","atrub2":"valuer2","atrub100":"value100gf45r"},
{"id":6,"code":"abc","atrub1":"value4321","atrub2":"valueq2","atrub100":"value100re"},
])



db.getCollection('orderTag').insert([
{"id":1,"code":"abc","tags":["a","b","c","d"]},
{"id":2,"code":"efg","tags":["a","c","g","f"]},
])

I want to merge 2 in 1 and 'orderTag' collection only need 'tags' and search by "tags" where include "b": I expect result is:

 [
{"id":1,"code":"abc","atrub1":"value1","atrub2":"value2","atrub100":"value100g","tags":["a","b","c","d"]},
{"id":2,"code":"abc","atrub1":"value11","atrub2":"value42","atrub100":"value100gr","tags":["a","b","c","d"]},
{"id":6,"code":"abc","atrub1":"value4321","atrub2":"valueq2","atrub100":"value100re","tags":["a","b","c","d"]},
]

I try it:

db.getCollection('orderTest').aggregate([
   {
      $lookup: {
         from: "orderTag",
         localField: "code",   
         foreignField: "code",  
         as: "fromItems"
      }
   },
   { $match: {
        $and: [
            {'fromItems.tags':'b'},
       ]}}
])

but 'tags' is so deep, It's not my expect result. How can I do?

Dino Fung
  • 1
  • 1
  • What result do you expect? If you actually show that, then we might understand what you are asking and be able to show you how to get that result. – Neil Lunn May 19 '18 at 03:28
  • I expect result is: [ {"id":1,"code":"abc","atrub1":"value1","atrub2":"value2","atrub100":"value100g","tags":["a","b","c","d"]}, {"id":2,"code":"abc","atrub1":"value11","atrub2":"value42","atrub100":"value100gr","tags":["a","b","c","d"]}, {"id":6,"code":"abc","atrub1":"value4321","atrub2":"valueq2","atrub100":"value100re","tags":["a","b","c","d"]}, ] – Dino Fung May 21 '18 at 01:14
  • That's what gets returned, so I don't see what the question is. Refer to the two marked duplicate questions as they might give your insight into what happens. You want get "just tags" from a join which contains more information than that without explicitly reshaping the document afterwards. – Neil Lunn May 21 '18 at 01:22
  • Please [edit your question](https://stackoverflow.com/posts/50421452/edit) and make things clearer. Read the linked duplicates and show you have applied something from there. Details do not belong in comments. – Neil Lunn May 21 '18 at 01:27

0 Answers0