cannot filter with $match a node by another subnodes value in MongoDB

86 Views Asked by At

environment: Mongo 4.2.2. invoking from Compass 1.20.5

I did $unwind 2 elements of an array (of a single document) into 2 single documents:

 {
    { id: 1 },
    { termTrg: { lang: "ara"} },
    { sublangTrans: { lang: "apj"} }
 }

and

 {
    { id: 1 },
    { termTrg: { lang: "ara"} },
    { sublangTrans: { lang: "ara"} }
 }

Before I $group them again by id 1 into one document, I wish to filter with $match documents where the lang attributes in a document are the same. Providing the string ara staticly, removes the second document as intended.

$match { 'sublangTrans.lang' : { $ne: 'ara' } }

If I try to replace the ara with the node's value of termTrg.lang, it does not remove any documents.

$match { 'sublangTrans.lang' : { $ne: 'termTrg.lang' } }

Why is termTrg.lang 's value not resolved? What is the correct syntax? Is there an alternative way to filter documents?

1

There are 1 best solutions below

0
thammada.ts On BEST ANSWER

The following will match the string that is not equal to termTrg.lang

$match { 'sublangTrans.lang' : { $ne: 'termTrg.lang' } }

To have get the resolved value of termTrg.lang, you have to use $expr https://docs.mongodb.com/manual/reference/operator/query/expr/

$match: { $expr: { $ne: ['$sublangTrans.lang', '$termTrg.lang'] } }

In case you want to match items that have the same lang attrubute

$match: { $expr: { $eq: ['$sublangTrans.lang', '$termTrg.lang'] } }