good day.

There are two collections, such as:

db.tags.find() {_id:ObjectID(...),"text":"text1", "tags":"tag1"}, {_id:ObjectID(...),"text":"text2", "tags":["tag2", "tag3"]}, {_id:ObjectID(...),"text":"text3", "tags":["tag1", "tag3"]} 

and

 db.tagdetails.find() {_id:ObjectID(...),"tagname":"tag1","det":"x"}, {_id:ObjectID(...),"tagname":"tag2","det":"y"} 

do $ lookup:

 db.tags.aggregate([{$project:{_id:0, tags:1, text:1}}, {$unwind:"$tags"}, {$lookup: {from:"tagdetails", localField:"tags", foreignField:"tagname", as:"t"}}]) 

everything seems to work, but the output is a collection like this:

 {"text":..., "tags":..., "t": [{"_id":..., "tagname":..., "det":...}]} 

more details:

 {"text":"posttext", "tags":"tag1", "t":[{"_id":ObjectID..., "tagname": "tag1", "det":"x"}]} {"text":"posttext2", "tags":"tag2", "t":[{"_id":ObjectID..., "tagname": "tag2", "det":"y"}]} {"text":"posttext2", "tags":"tag3", "t":[]} {"text":"posttext3", "tags":"tag1", "t":[{"_id":ObjectID..., "tagname": "tag1", "det":"x"}]} {"text":"posttext3", "tags":"tag3", "t":[]} 

Ie, clearly, lukap puts the document from the second collection entirely. I do not need it. need to get a document of the form:

 {"text":..., "tags":..., "det":...} 

Those. There is only one field from the second collection. I can not figure out how to do it. I cannot exclude it using $ project, an error appears:

 The top-level _id field is the only field currently supported for exclusion 
  • Please remove all these ... and write down these fields. Also tell me how many elements are in the array after $lookup ? - styvane
  • Values ​​_id, of course, have the form ObjectId ("59624671bf7c5ea69b2d6206"). I see absolutely no point in writing here. The specified aggregate command returns 5 documents. The result of her work was edited - user211576
  • When you ask a question in MongoDB, I am very convinced that you wrote a valid BSON document. If you think what to write some fields, then write one ... in the place of them. Some non-opaque MongoDB users would like to check their local response before writing it on the site. I know what I'm talking about - styvane
  • I see no reason to write krakozabry type ObjectId ("59624671bf7c5ea69b2d6206"). _id is a standard id field that mongo automatically adds with similar identifiers - user211576
  • The amendment you have proposed is, in my opinion, wrong, and misleading. The db.collection.find () command, of course, will display the contents of the collection documents along with the _id field; you do not need to remove it as unnecessary. It is possible that it is really unnecessary, but still this command displays it. The specified lookup also inserts a document from the attached collection, along with the _id field from this collection. - user211576

1 answer 1

After $ lookup, make $ unwind on the "t" field and then use $ project with the required fields.