Hi everyone,
seeking help with an aggregations query. I have a collection Matches
which has transactional data in it, identified by kit1
and kit2
.
This is a sample doc (other fields hidden for simplicity):
{ “_id” : “P5M5NzYGJ5aKk5FSv”, “kit1” : “7jVr2Hul1Vae3bqRVhyKA”, “kit2” : “7lljS20fzXF-uv2aAh3WE” }
I’m querying for all Matches
docs where either kit1
or kit2
is equal to a certain identifier (kitRemove') and want to return the identifier that is not
kitRemove` (using Meteor framework in my app - hence the use of JavaScript code):
const kitsWithRelationArray = await MatchesRaw.aggregate([
{ $match: { $or: [{ kit1: kitRemove }, { kit2: kitRemove }] } },
{ $project: { kit: { $cond: { if: { $eq: ["$kit1", kitRemove] }, then: "$kit2", else: "$kit1" } }, _id: 0 } },
], { session: mongoSession }).toArray();
This is the result I get from the above query:
I’m facing two problems with the result:
- I get some
kit
identifiers as duplicates because more than 1Matches
doc can exist for the samekit1
vskit2
combination.
Example:
{ “_id” : “troqybYEBCPB97cDr”, “kit1” : “7jVr2Hul1Vae3bqRVhyKA”, “kit2” : “85n_Re9XRQCiYQd-VxzhV” }
{ “_id” : “YKXKhaNf7xCrihFPM”, “kit1” : “7jVr2Hul1Vae3bqRVhyKA”, “kit2” : “85n_Re9XRQCiYQd-VxzhV” }
Question 1: How can avoid getting duplicate values like this?
- I’m currently getting an array of objects back. While I can certainly handle that, it would be nicer to just get an array of those unique identifiers like this:
[“7lljS20fzXF-uv2aAh3WE”, “7pgnWX288a3V0RdIF-zlq”, “85n_Re9XRQCiYQd-VxzhV”]
Question 2: How can I alter the query to get an array of strings (kit
) back?
Many thanks in advance, still learning all the bits and pieces of MongoDb’s powerful functions.