How to query $in with objectid in meteors existing collection - mongodb

I am using existing Mongodb in meteor. I don't know how to query $in with ObjectId()
Users = new Mongo.Collection('users', {idGeneration: 'MONGO'});
var ids = ['55549158f046be124e3fdee7',
'5539d937f046be0e2502aefc',
'55548e10f046bee14c3fdeed',
'55549938f046be99493fdef8' ];
Users.find({_id:{$in: ids}}).fetch(); //returns empty array

You could first cast the array ids to an array of ObjectIds using the map() method:
var Users = new Mongo.Collection('users', {idGeneration: 'MONGO'}),
ids = [
'55549158f046be124e3fdee7',
'5539d937f046be0e2502aefc',
'55548e10f046bee14c3fdeed',
'55549938f046be99493fdef8'
],
mids = ids.map(function(id) { return new Mongo.ObjectID(id); });
Users.find({"_id":{"$in": mids}}).fetch();

Related

MongoDB return all documents (even if they are double)

Let say I have an array with some document _id's:
const ids = ["5ffd5eb822084969b4dc9f74","5ffd5eb822084969b4dc9f74"]
As you can see, there are duplicated, so I want both documents back from Mongo. But with the Document.find({_id: {$in: ids}}) query and the $all option only one document is returned.
Is there a way to get the transaction twice (in this case) back from Mongo?
You can use a for loop iterate over the array of ids and and use Document.find(id) multiple times.
const ids = ["5ffd5eb822084969b4dc9f74","5ffd5eb822084969b4dc9f74"];
const result = [];
// Loop through each element
ids.forEach(async(id) => {
const foundResult = await Document.find({_id: id});
result.push(foundResult);
})
Then you can use the result array.

Mongodb: Query and array with an array

I'm kind of stuck how to query an array with an array, in mongodb.
In the below example, "tag" is a string - and "newTotalTags" is an array of tags.
let allShares = await ShareModel.find({tag: { $in: newTotalTags}}).lean()
I need to change this logic from tag (single string) to tags (array).
So I have an array (newTotalTags) and I need to query a schema property which is also an array.
Any tips?
you can try $all instead of $in,
let allShares = await ShareModel.find({ tag: { $all: newTotalTags } }).lean()
Playground

Is There a way to fetch data from mongodb Collection using in Array function. if array id is string

I have Generating the Dynamic Report from mongodb Collections. I fetch Data from one Collection and e.g client and take all client id in Array e.g ["5b7869dff0be71721f53d2e3","5b7869dff0be71721f53d2e4","5b7869dff0be71721f53d2e3"] When i I fetch data from other collection using In Array e.g {"clientId": { $in: inArray } } it give me empty result. because in array work if i put { "clientId": { $in: [ObjectId('5b785f243cc6c746af635dc8')] } } "ObjectId" word before the id. My Question is how i Put this ObjectId work in the array.
you can use map to map the array to an array of ObjectId
inArray = inArray.map( value => ObjectId(value) );

MongoDB: projection on specific fields of all objects in an array

I have a MongoDB database with following data structure for one Part:
Part Data structure
Now I want to to have a projection on the element Descriptionof every object in the array SensorData. Using the MonogDB API in .NET with C# my code would look the following:
var projection = Builders<Part>.Projection
.Include(part => part.SensorData[0].Description)
.Include(part => part.SensorData[1].Description)
.Include(part => part.SensorData[2].Description)
//...
;
The problem is that the number of objects in SensorData is dynamic and may range from 0 to about 20, so including every Descriptionfield for itself is not possible. The projection has to be done Server-Side as SensorData -> Values can be huge.
Is there any Syntax or method to do this kind of projection?
Just found a solution after asking a colleague: It isn't possible to do this with the Projection Builder, but it is with the aggregation framework:
var match = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"PartData.Description", 1 }
}
}
};
var pipeline = new[] { match };
var aggregationCursor = parts.Aggregate<Part>(pipeline);
var query = aggregationCursor
.ToEnumerable()//needed to perform AsQueryable
.AsQueryable()//Asking for data elements
}

mongodb java to insert embedded document

I have a collection with embedded documents in it.
System
{
System_Info: ...,
Tenant: [
{
Tenant_Id: ...,
Tenant_Info: ...,
Prop_Info: ...
},
{
Tenant_Id: ...,
Tenant_Info: ...,
Prop_Info: ...
} ]
}
If I need to insert another tenant information like this
Tenant { Tenant_Id:2,Tenant_Info:"check",prop_info:"client"}.
whats the mongodb query to insert embedded documents? and how to do it using java?
Use the following code to insert into array :
BasicDBObject query = new BasicDBObject();
query.put( "System_Info", "...." );
BasicDBObject tenant = new BasicDBObject();
tenant.put("Tenant_Id", 2);
tenant.put("Tenant_Info", "check");
tenant.put("Prop_Info", "client");
BasicDBObject update = new BasicDBObject();
update.put("$push", new BasicDBObject("Tenant",tenant));
coll.update(query, update,true,true);
Are you trying to add another Tenant into the array? If so, you would want to create a DBObject representing the Tenant, and then $push it onto the array.
In Java, embedded documents are represented by DBObjects (of which BasicDBObject is a subclass). Here is an example of inserting an embedded document, from the docs:
http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-InsertingaDocument
Additionally, here is an example of using $push in Java:
Updating an array in MongoDB using Java driver
...and this is how to do it with mongo-driver version >= 3.1 (mine is 3.2.2):
Document tenant = new Document("Tenant_Id", 2)
.append("Tenant_Info", "check")
.append("Prop_Info", "client");
Bson filter = Filters.eq( "System_Info", "...." ); //get the parent-document
Bson setUpdate = Updates.push("Tenant", tenant);
coll.updateOne(filter, setUpdate);
Hope that helps someone.