[英]MongoDB select where in array of _id?
is possible in mongo db to select collection's documents like in SQL :可以在 mongo db 中像在 SQL 中一样选择集合的文档:
SELECT * FROM collection WHERE _id IN (1,2,3,4);
or if i have a _id array
i must select one by one and then recompose the array/object
of results?或者如果我有一个
_id array
我必须一一选择,然后重新组合结果的array/object
?
Easy :)简单 :)
db.collection.find( { _id : { $in : [1,2,3,4] } } );
taken from: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in取自: http : //www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in
Because mongodb uses bson
and for bson is important attribute types.因为 mongodb 使用
bson
并且 bson 是重要的属性类型。 and because _id
is ObjectId
you must use like this:并且因为
_id
是ObjectId
你必须像这样使用:
db.collection.find( { _id : { $in : [ObjectId('1'),ObjectId('2')] } } );
and in mongodb compass
use like this:在
mongodb compass
使用如下:
{ "_id" : { $in : [ObjectId('1'),ObjectId('2')] } }
Note: objectId in string has 24
length.注意:字符串中的 objectId 长度为
24
。
You can try this你可以试试这个
var ids = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"];
var oids = [];
ids.forEach(function(item){
oids.push(new ObjectId(item));
});
.find({ _id: {$in : oids}})
if you want to find by user and also by another field like conditionally, you can easily do it like beneath with spread and ternary operator using aggregate
and match
如果您想按用户以及有条件地按另一个字段查找,您可以使用
aggregate
和match
轻松地使用扩展和三元运算符进行如下操作
const p_id = patient_id;
let fetchingReports = await Reports.aggregate([
...(p_id
? [
{
$match: {
createdBy: mongoose.Types.ObjectId(id),
patient_id: p_id,
},
},
]
: [
{
$match: {
createdBy: mongoose.Types.ObjectId(id),
},
},
is possible in mongo db to select collection's documents like in SQL :可以在mongo db中像在SQL中那样选择集合的文档:
SELECT * FROM collection WHERE _id IN (1,2,3,4);
or if i have a _id array
i must select one by one and then recompose the array/object
of results?还是如果我有一个
_id array
我必须一个一个地选择,然后重新组成结果的array/object
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.