我的集合中有一个文档具有以下属性:
nodeid : long
type: string
bagid: long
因此,节点可以位于一个包上,并且可以是不同类型的。
我需要找到, 给定节点列表中的所有 A 类型节点、或 B 类型节点、给定包中的或 C 类型节点。
如何在 MongoDB 中设计该查询?我有所有 IN 子句,但这是提高性能的有效方法。你能指出我正确的方向吗?我找不到可以帮助我简化此操作的聚合或减少。
我还尝试使用三个元素进行文本搜索,但在文本搜索中使用 or ,例如“类型:A\”类型:B 节点:X\”\“类型:B 节点:Y\”等等,不起作用。
谢谢
编辑,添加示例:
{ "_id" : BinData(3,"NJUuYHEBAAAdCda3V+kXvg=="),
"type" : "question", "bagid" : NumberLong(1067),
"topics" : [ NumberLong(33), NumberLong(67), NumberLong(203), NumberLong(217) ],
"nodeid" : NumberLong(15855),
"creationDate" : ISODate("2020-04-09T18:23:17.812Z"),
"_class" : "com.test.NodeEvent" }
{ "_id" : BinData(3,"NJUuYHEBAAAdCda3V+kXvg=="),
"type" : "comment", "bagid" : NumberLong(1067),
"topics" : [ NumberLong(33), NumberLong(67), NumberLong(203), NumberLong(217) ],
"nodeid" : NumberLong(15857),
"creationDate" : ISODate("2020-04-09T18:23:17.812Z"),
"_class" : "com.test.NodeEvent" }
{ "_id" : BinData(3,"NJUuYHEBAAAdCda3V+kXvg=="),
"type" : "question", "bagid" : NumberLong(1069),
"topics" : [ NumberLong(33), NumberLong(67) ],
"nodeid" : NumberLong(15859), "creationDate" : ISODate("2020-04-09T18:23:17.812Z"),
"_class" : "com.test.NodeEvent" }
最佳答案
您可以使用 MongoDB 查询语言构建查询。该查询是使用 db.collection.find 编写的方法。它使用各种查询运算符,例如 $or , $in ,和$and .
I need to find, all nodes of type A, or nodes of type B in a given list of nodes, or, nodes of type C in a given bag. How can I design that query in mongo?
db.collection.find( { $or: [
{ type: "A" },
{ type: "B", node: { $in: [ "A", "C" ] },
{ type: "C", bag: 130 }
]
} );
在上面的查询中,条件 { type: "C", bag: 130 }
相当于 { $and: [ { type: "C""}, { bag: 130 } ] } }
.条件 { type: "B", node: { $in: [ "A", "C"] }
也是如此。但是,在本例中,使用 $and
是可选的(有关详细信息,请参阅文档)。
The query would be something like, given bag 1067 give me all nodes with topics: 33 or 203
db.collection.find( { bag: 1067, topics: { $in: [ 33, 203 ] } } )
输出取决于集合中的数据。 find
方法返回一个光标,您可以应用各种 cursor methods在返回的文档上(例如,您可以按字段对它们进行排序)。
关于java - 尝试查询 MongoDB 数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130816/