猫鼬用嵌套的对象数组查找查询

时间:2021-03-10 16:54:13

标签: mongodb mongoose

我有一个用户数据集合和一个朋友列表,其中包含一个嵌套的对象数组。

{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"}]}

我正在尝试查找朋友姓名为“A”的查询。 我得到了两条包含所有数据的记录。
我尝试使用以下查询。

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

当前输出:

{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: "abcd", friends: [{name: "A", status : "active", code: "X1"}]}
{username: "xyz", friends: [{name: "A", status : "active", code: "X1"}]}

结果应该只返回名称为“A”的对象。其他对象数据不应返回..

你能帮助构建类似上面输出的查询吗。

1 个答案:

答案 0 :(得分:0)

您可以这样使用 projection

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

示例here