0

I have a data like below in MongoDB.

const A = { uid: '1234',
            works: [
           { name: 'car',
             item:['tire','wheel']
           },
           { name: 'ship',
             item:['tire','wheel']
           }
           ]

My goal is to find whether the name duplicated exists or not.
In conclusion, I want to get only the names.
So 'res.send(result)' gives me like '[car, ship]'. But the code below doesn't work. How can I make that function? Thank you so much.

const workName = await User.findOne({
      uid: userID, works:{$in:['name']}
    });

1 Answer 1

1

The easy way is to find the aggregate of name and check if the count is greater than one. Since it is inside the the array we need to unwind it.

The below query works, to detect if a sub document contain duplicates for each document.

db.getCollection('collection_name').aggregate([{"$unwind":"$works"} ,{"$group":{"_id":{"name":"$works.name","uid":"$uid"},"count":{"$sum":1}}},{"$match":{"count":{"$gte":2}}}])

if you want to find in all the documents remove uid from _id of group.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.