Does the $slice function in MongoDB Meteor work? - mongodb

Does the $slice function work in Meteor MongoDB?
Here is some query sample:
Posts.find({"permalink":"udrskijwddhigfwhecxn"},{"comments":{"$slice":10}});
I tried querying in the mini MongoDB and directly through publish using parameters, but it always return the complete nested data.
{
_id:Object(1231o2j3lkqj),
body:"this is body",
author:"machine",
permalink:"udrskijwddhigfwhecxn"
title:"this is title",
tags: ["dog","cat","tree"]
comments: [{
body:"comment body",
author:"lara",
email:"email#ab.com"
},
...]
date:ISODate("2013-03-16T02:50:27.881Z")
}

you can split the following. by using The projection in Meteor and it is specified by fields.
Posts.find({"permalink":"udrskijwddhigfwhecxn"},
{
fields:{"comments":{"$slice":1‌​0}}
})

Related

mongoose reference to array like array[0] in find filter

I had a weird issue. I've been using mongodb and mongoose for sometime and never had an array filtering. Today I had to do it and I'm stuck.
How do you access array stored in mondodb using the traditional way array[0]?
My array stored in my db as the following:
_id:6262013fa90e7b533809140d
isactive:true
schedule:Array
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
name:"whatever"
description:"describe somthing"
so many questions about mongoose arrays online and yet the doc is not showing any examples.
So now if I want to access the array schedule[0] value. How do I filter the find({"schedule[0]" : "object.name"})
Or how do you access arrays in general in Mongoose? The doc is so poor and no examples about it online.
How do I update schedule[2] or schedule[3] in that array using mongoose?
schedule[0] object has the following data:
0:Object
weekdayname:"Monday",weekdaynumber:1,
openhours:"10",
closehours:"10"
openminutes:"00"
closeminutes:"00"
openampm:"AM",closeampm:"PM"
to update schedule[0].openhours, what should I do?
Query
db.collection.find({
"schedule.weekdayname": "Monday"
},
{
"schedule.$": 1
})
mongoplayground
mongoose find
Update
db.collection.update({
"schedule.weekdayname": "Monday"
},
{
$set: {
"schedule.$.openhours": "11"
}
},
{
multi: true
})
mongoplayground
mongoose update

Mongo Atlas Search Index numeric field exact match search

We are using MongoDB Atlas Search Indexes to query and filter the documents list. consider below document.
{_id:5sfgdfgf2c46e0fb00019bdecc,
user_id:4996,
bom_number:"112",
name:"test"}
Created default Index:
{
"mappings": {
"dynamic": false,
"fields": {
"user_id": {
"type": "string"
}
}
}
}
Query:
{
text: {
query: ["4996","3888"],
path: 'user_id'
}
}
It is not returning any documents. Can anyone please guide. I know we actually stored user_id as numeric form and I tried indexing and querying the field as String. Please help me out and suggest correct way of querying mongo atlas numeric field with multiple values.
$search is what you need to use to query using the index that you have created and you also need to mention the name of the index in the query.
The below draft might help you:
$search:{
{
index: "index_name_created_from_atlas_search",
text: {
query: "<actual data you need to search>",
path: "<field_name>"
}
}
}
And based on your example, if you want to have multiple conditions with the search, you can refer to official documentation here of all sorts of multiple conditions you can integrate with the $search aggregation using the compound operator.

Mongoose Updating an array in multiple documents by passing an array of filters to update query

I have multiple documents(3 documents in this example) in one collection that looks like this:
{
_id:123,
bizs:[{_id:'',name:'a'},{_id:'',name:'b'}]
},
{
_id:456,
bizs:[{_id:'',name:'e'},{_id:'',name:'f'}]
}
{
_id:789,
bizs:[{_id:'',name:'x'},{_id:'',name:'y'}]
}
Now, I want to update the bizs subdocument by matching with my array of ids.
That is to say, my array filter for update query is [123,789], which will match against the _id fields of each document.
I have tried using findByIdAndUpdate() but that doesn't allow an array for the update query
How can I update the 2 matching documents (like my example above) without having to put findByIdAndUpdate inside a forloop to match the array element with the _id?
You can not use findByIdAndUpdate when updating multiple documents, findByIdAndUpdate is from mongoose which is a wrapper to native MongoDB's findOneAndUpdate. When you pass a single string as a filter to findByIdAndUpdate like : Collection.findByIdAndUpdate({'5e179dac627ef7823643cd97'}, {}) - then mongoose will internally convert string to ObjectId() & form it as a filter like :_id : ObjectId('5e179dac627ef7823643cd97') to execute findOneAndUpdate. So it means you can only update one document at a time, So if you've multiple documents to be updated use update with option {multi : true} or updateMany.
Assume if you wanted to push a new object to bizs, this is how query looks like :
collection.updateMany({ _id: { $in: [123, 456] } }, {
$push: {
bizs: {
"_id": "",
"name": "new"
}
}
})
Note : Update operations doesn't return the documents in response rather they will return write result which has information about n docs matched & n docs modified.

How to extract the creation date of _id and add it as a new field using the aggregation framework?

I have been trying for a while to extract the insertion date of a mongodb document and add it as a new field to the same document.
I'm trying to do it using the mongo and mongo shell aggregation framework without getting good results.
Here is my query
db.getCollection('my_collection').aggregate(
[
{
$match: {
MY QUERY CRITERIA
}
},
{
$addFields: { "insertTime": "$_id.getTimestamp()" }
}
]
)
I am trying to extracr insertion time from _id using the function getTimestamp() but for sure there is somtehing about aggregation framework syntax that I am missing because I can not do what I am trying to do in my query.
This works perfect:
ObjectId("5c34f746ccb26800019edd53").getTimestamp()
ISODate("2019-01-08T19:17:26Z")
But this does not work at all:
"$_id.getTimestamp()"
What I am missing?
Thanks in advance

MongoDB: distinct tuples

Suppose to have a collection of MongoDB documents with the following structure:
{
id_str: "some_value",
text: "some_text",
some_field: "some_other_value"
}
I would like to filter such documents so as to obtain the ones with distinct text values.
I learned from the MongoDB documentation how to extract unique field values from a collection, using the distinct operation. Thus, by performing the following query:
db.myCollection.distinct("text")
I would obtain an array containing the distinct text values:
["first_distinct_text", "second_distinct_text",...]
However, this is not the result that i would like to obtain. Instead, I would like to have the following:
{ "id_str": "a_sample_of_id_having_first_distinct_text",
"text": "first_distinct_text"}
{ "id_str": "a_sample_of_id_having_second_distinct_text",
"text": "second_distinct_text"}
I am not sure if this can be done with a single query.
I found a similar question which, however, do not solve fully my problem.
Do you have any hint on how to solve this problem?
Thanks.
You should look into making an aggregate query using the $group stage, and probably using the $first operator.
Maybe something along the lines of:
db.myCollection.aggregate([{ $group : { _id : { text: "$text"},
text: { $first: "$id_str" }
}
}])
try:
db.myCollection.aggregate({$group: {_id: {'text': "$text", 'id_str': '$id_str'}}})
More information here: http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/