MongoDB,如何合并2个集合和搜索合并数据(不是简单的合并)

时间:2018-05-19 03:22:50

标签: mongodb join merge

我在mongoDB中有2个集合:

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"]},
])

我想合并2合1和' orderTag'收藏只需要'标签'并按"标签搜索"包括" b": 我希望结果是:

 [
{"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"]},
]

我试试看:

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

但是'标签'太深了,这不是我期望的结果。 我该怎么办?

0 个答案:

没有答案