Keep field up to date, with occurence of field in other collection in mongodb

Keep field up to date, with occurence of field in other collection in mongodb



I'm quite new to mongodb and can't figure out how to make the value of a field the result of a certain function on another field. To give an example:



collection names:


names


"name1" : "a", "name2" : "b"
"name1" : "c", "name2" : "a"



collection occurrences:


occurrences


"name" : "a", "occurrences" : <function on names>
"name" : "b", "occurrences" : <function on names>
"name" : "c", "occurrences" : <function on names>



My goal is to have the field occurrences representing the times the certain name occurs in the collection names, e.g. "name": "a", "occurrences":2.


occurrences


names


"name": "a", "occurrences":2



I looked through the documentation and found the function $count, but I can't see how to implement it in a field instead of a call to the database.


$count



Thank you for your help!






What about the answer?

– Anthony Winzlet
Dec 11 '18 at 17:14




1 Answer
1



You can try below aggregation


db.occurrences.aggregate([
"$lookup":
"from": "names",
"let": "name", "$name" ,
"pipeline": [
"$match": "$expr":
"$or": [
"$eq": ["$name1", "$$name"] ,
"$eq": ["$name2", "$$name"]
]
,
"$count": "count"
],
"as": "occurrences"
,
"$project":
"name": 1, "occurrences": "$arrayElemAt": ["$occurrences.count", 0]

])



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy