0

I have a collection of user's data with a friends list that has a nested array of objects.

{username: "abcd", friends: [{name: "A", status : "active", code: "X1"},{name: "B", status : "inactive", code: "X2"}, {name: "B", status : "active", code: "X3"}]}
{username: "xyz", friends: [{name: "A", status : "active", code: "X1"},{name: "E", status : "inactive", code: "X2"}, {name: "F", status : "active", code: "X3"}]}
{username: "xyz", friends: [{name: "X", status : "active", code: "X1"},{name: "E", status : "inactive", code: "X2"}, {name: "F", status : "active", code: "X3"}]}

I am trying to find a query with who are have friends name is "A". I am getting two records with all data.
I tried using the below query.

users.find({"friends.name" : "A"});

Current output:

{username: "abcd", friends: [{name: "A", status : "active", code: "X1"},{name: "B", status : "inactive", code: "X2"}, {name: "B", status : "active", code: "X3"}]}
{username: "xyz", friends: [{name: "A", status : "active", code: "X1"},{name: "E", status : "inactive", code: "X2"}, {name: "F", status : "active", code: "X3"}]}

Expected Output:

{username: "abcd", friends: [{name: "A", status : "active", code: "X1"}]}
{username: "xyz", friends: [{name: "A", status : "active", code: "X1"}]}

The result should return only who have name is "A".. Other objects data should not return..

Can you help to build query like above output.

RSKMR
  • 1,812
  • 5
  • 32
  • 73
  • see [$filter](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/index.html) operator, you can use this in projection of find() from mongodb v4.4. – turivishal Mar 10 '21 at 16:57

1 Answers1

0

You can use projection in this way:

db.collection.find({
  "friends.name": "A"
},
{
  "username": 1,
  "friends.$": 1
})

Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65