我有集合Collection1
,我需要获取一个数组:[id1, id2, id3, ...]
(对于此集合中的每个元素,由_id`s组成的数组)。有没有办法用MongoDB工具进行此查询?谢谢!
答案 0 :(得分:0)
您必须对cursor.toArray()
的结果使用find
函数,其投影文档仅投影_id
,即ObjectId()
值
MongoDB Enterprise > db.users.find().pretty()
{
"_id" : ObjectId("570e1d465a44f125ef156791"),
"name" : "Ritesh Talreja",
"age" : 22,
"gender" : "M"
}
{
"_id" : ObjectId("570e1e1d5a44f125ef156792"),
"name" : "Saloni",
"age" : 21,
"gender" : "F"
}
{
"_id" : ObjectId("570e1e485a44f125ef156793"),
"name" : "abcd",
"age" : 22,
"gender" : "M"
}
{
"_id" : ObjectId("570e28d45a44f125ef156794"),
"name" : "Saloni",
"age" : 21,
"gender" : "F"
}
{ "_id" : 123 }
MongoDB Enterprise > db.users.find({}, {_id:1}).toArray()
[
{
"_id" : ObjectId("570e1d465a44f125ef156791")
},
{
"_id" : ObjectId("570e1e1d5a44f125ef156792")
},
{
"_id" : ObjectId("570e1e485a44f125ef156793")
},
{
"_id" : ObjectId("570e28d45a44f125ef156794")
},
{
"_id" : 123
}
]
MongoDB Enterprise >
作为补充,您还可以使用:
MongoDB Enterprise > db.users.distinct("_id")
[
123,
ObjectId("570e1d465a44f125ef156791"),
ObjectId("570e1e1d5a44f125ef156792"),
ObjectId("570e1e485a44f125ef156793"),
ObjectId("570e28d45a44f125ef156794")
]
MongoDB Enterprise >