gpt4 book ai didi

MongoDB:通过多个条件查询嵌套数组

转载 作者:可可西里 更新时间:2023-11-01 10:28:53 28 4
gpt4 key购买 nike

假设这是我的用户收藏中的一项:

  {
"_id" : "5545f4c4d0dd52c355a99fbe",
"name" : "Dollie James",
"device" : "iOS",
"gender" : "Female",
"wallet" : [
{
"store" : "All Saints",
"balance" : "$196.11",
"date" : "2014-02-22T22:09:38 -10:00",
"tags" : [
"Tshirt",
"Summer"
]
},
{
"store" : "Nike",
"balance" : "$367.76",
"date" : "2014-04-18T14:44:30 -10:00",
"tags" : [
"Shoes"
]
}
]
}

此记录是从以下查询返回的:

db.users.findOne({$and:[{"wallet.tags": "Tshirt"}, {"wallet.store":"Nike"}]})

但这不是我想要的结果,因为 Tshirt 和 Nike 在 wallet 数组中不在同一个对象中。似乎 mongo 正在对整个数组进行查询。我如何定位此查询以仅返回数组中同一对象中的两个条件?

最佳答案

您不需要$and(因为它将独立应用条件)但是$elemMatch .来自文档:

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

在您的具体情况下:

> db.wallet.find(
{wallet: { $elemMatch:{"tags" : "Tshirt", "store":"Nike"}}}
).pretty()
{
"_id" : "5545f4c4d0dd52c355a99f00",
"name" : "Working example",
"device" : "iOS",
"gender" : "Female",
"wallet" : [
{
"store" : "Nike",
"balance" : "$196.11",
"date" : "2014-02-22T22:09:38 -10:00",
"tags" : [
"Tshirt",
"Summer"
]
}
]
}

关于MongoDB:通过多个条件查询嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30013149/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com