gpt4 book ai didi

mongodb - 在 mongodb(或 java)中按数组查找对象

转载 作者:可可西里 更新时间:2023-11-01 09:58:13 26 4
gpt4 key购买 nike

我有一个这样的集合(数据集):

{
"_id" : ObjectId("515611c1c6e3718ee42a5655"),
"id": "Product1",
"type": "ProductType4"
"productFeature": [
{
"id": "ProductFeature1"
},
{
"id": "ProductFeature2"
},
{
"id": "ProductFeature3"
}
]
"productPropertyNumeric": 25
},
... and more product objects...

{
"_id" : ObjectId("515611c1c6e3718ee42a5666"),
"id": "ProductFeature1",
"label": "blablabla"
},
{
"_id" : ObjectId("515611c1c6e3718ee42a5667"),
"id": "ProductFeature2",
"label": "blebleble"
},
{
"_id" : ObjectId("515611c1c6e3718ee42a5668"),
"id": "ProductFeature3",
"label": "blublublu"
} ... and more feature objects...

根据 Product1,我必须在其“productFeature”数组中找到特定产品的特征和标签。

我已经尝试在 Mongo shell 中找到它们(例如使用变量):

var aaa = db.dataset.find({ id: "Product1" })

db.dataset.find({ id: "aaa.productFeature.id" })

但它不起作用。如果有人知道如何按数组查找对象,请帮助我。非常感谢。

PS:最好是用 Java - 例如,我应用了一个查询:

    BasicDBObject query = new BasicDBObject();

query.put("type","ProductType4");
query.put("productPropertyNumeric", new BasicDBObject("$gt", 10));

DBCursor cursor = coll.find(query).sort( new BasicDBObject("label", 1));
while (cursor.hasNext()){
System.out.println(cursor.next().get("id"));
}

最佳答案

这是我对自己问题的回答。我希望这对某人有所帮助。

BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();

query.put("id", "Product1");
field.put("id", 1);
field.put("productFeature", 1);
field.put("_id", 0);

DBCursor cursor = coll.find(query, field);
while (cursor.hasNext()) {
BasicDBObject result = (BasicDBObject) cursor.next();
System.out.println(result);
ArrayList<BasicDBObject> features = (ArrayList<BasicDBObject>) result.get("productFeature");

for (BasicDBObject embedded : features) {
String featuresId = (String) embedded.get("id");

BasicDBObject query2 = new BasicDBObject();
BasicDBObject field2 = new BasicDBObject();

query2.put("id", featuresId);
field2.put("id", 1);
field2.put("label", 1);
field2.put("_id", 0);
DBCursor cursor2 = coll.find(query2, field2);

while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
}
}

关于mongodb - 在 mongodb(或 java)中按数组查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713378/

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