我希望通过Id获取所有文档,如下面的SQL查询:
Select * from table
where subdoc1.id in (1234, 2345, 3456)
or subdoc2.id in (1234, 2345, 3456)
这是我的文件的结构:
{
"id" : new ObjectId("234565"),
"subdocs1" : [ {
"id" : "1234",
... },
{
"id": "2345",
... }],
"subdocs2" : [ {
"id" : "3456",
... },
{
"id": "7890",
... }]
}
MongoDB中的查询怎么样?
答案 0 :(得分:0)
db.collection.find({
$and : [{"subdocs1._id": {"$in" : ["1234", "2345", "3456"]},
{"subdocs2._id": {"$in" : ["1234", "2345", "3456"]}}]
})
OR
db.collection.find({
$and : [{"subdocs1":{"$elemMatch" : {"$_id" : {"$in" : ["1234", "2345", "3456"]}}}},
{"subdocs2:{"$elemMatch" : {"$_id" : {"$in" : ["1234", "2345", "3456"]}}}}]
})
答案 1 :(得分:0)
这是我的查询,有效:
db.getCollection('documents').find({
$or : [
{ "subdoc1._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc2._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc3._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } },
{ "subdoc4._id" : { "$in" : [ new ObjectId("5807a60afc84c80a5ea86218"), new ObjectId("5808ac5cfc841deda17f827b") ] } }
]})
感谢名单!!