Database

[{"collection":"faces","count":100,"content":{"name":{"type":"stringFromParts","parts":[{"type":"autoincrement","autoType":"int"}]},"img_path":{"type":"stringFromParts","parts":[{"type":"constant","constVal":"1_"},{"type":"autoincrement","autoType":"int"}]},"embedding":{"type":"array","minLength":512,"maxLength":512,"arrayContent":{"type":"double","min":-0.6,"max":1.8}}}},{"collection":"target","count":1,"content":{"embedding":{"type":"array","minLength":512,"maxLength":512,"arrayContent":{"type":"double","min":-0.6,"max":1.8}}}}]

Query

db.faces.aggregate([/** go get the target embedding*/{"$lookup":{"from":"target","pipeline":[],"as":"target"}},{"$set":{"target_embedding":{"$first":"$target.embedding"},"target":"$$REMOVE"}},/** done getting target embedding** calculate cosine similarity params*/{"$project":{"name":1,"img_path":1,"cos_sim_params":{"$reduce":{"input":{"$range":[0,{"$size":"$embedding"}]},"initialValue":{"dot_product":0,"doc_2_sum":0,"target_2_sum":0},"in":{"$let":{"vars":{"doc_elem":{"$arrayElemAt":["$embedding","$$this"]},"target_elem":{"$arrayElemAt":["$target_embedding","$$this"]}},"in":{"dot_product":{"$add":["$$value.dot_product",{"$multiply":["$$doc_elem","$$target_elem"]}]},"doc_2_sum":{"$add":["$$value.doc_2_sum",{"$pow":["$$doc_elem",2]}]},"target_2_sum":{"$add":["$$value.target_2_sum",{"$pow":["$$target_elem",2]}]}}}}}}}},{"$project":{"name":1,"img_path":1,"cos_sim":{"$divide":["$cos_sim_params.dot_product",{"$sqrt":{"$multiply":["$cos_sim_params.doc_2_sum","$cos_sim_params.target_2_sum"]}}]}}},{"$match":{"cos_sim":{"$lte":0.68}}}])

Result